1、首先新建一个空的web项目,在Program.cs中打开和使用session
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddSession(); builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseSession(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapDefaultControllerRoute(); app.Run(); } }
2、设置session扩展,新建SessionExtension类
public static class SessionExtension { public static void SetObject(this ISession session, string key, object value) { session.SetString(key, JsonConvert.SerializeObject(value)); } //获取对象方法 public static T GetObject<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } }
3、新建控制器基类
public class BaseController:Controller { protected UserInfo CurrentUser { get { return HttpContext.Session.GetObject<UserInfo>("userinfo"); } set { HttpContext.Session.SetObject("userinfo", value); } } }
4、新建控制权限和登陆的鉴权授权属性类,如果不符合要求则进行跳转
public class AuthAttribute: Attribute, IAuthorizationFilter { private string Roles; public AuthAttribute() { Roles = string.Empty; } public AuthAttribute(string roles) { Roles = roles; } public void OnAuthorization(AuthorizationFilterContext filterContext) { UserInfo userinfo = (UserInfo)filterContext.HttpContext.Session.GetObject<UserInfo>("userinfo"); if (userinfo == null) { filterContext.Result = new RedirectToActionResult("index","login",null); } }
5、新建两个控制器,一个为登陆使用,一个为主页面,显示session中的用户信息
logincontroller.cs
public class LoginController : BaseController { public IActionResult Index() { return View(); } [HttpPost] public IActionResult Login([FromForm] string userId, [FromForm] string passWord) { UserInfo userInfo = new UserInfo() { userName = "超级管理员", rolesName="管理员、查询、添加、编辑" }; CurrentUser = userInfo; return RedirectToAction("index","home"); } }
homecontroller.cs
[Auth] //用来控制权限及是否登陆 public class HomeController : BaseController { public IActionResult Index() { return View(CurrentUser); } }
测试一下,先启动,会进home界面,触发auth判断,没有session返回到login界面,登陆后重新进入home界面,model传入到显示页面中(略),问题完成。
标签:core,string,app,value,class,session,net,public From: https://www.cnblogs.com/youyuan1980/p/16990438.html