1.今日任务:优化登录后分角色显示页面
2.核心代码和效果图:
效果图:
对页面文本框验证写了长度限制和不能为空提示:
public async Task<bool> Login(string u_name, string u_pwd) { using (IDAL.IUserService userSvc = new DAL.UserService()) { return await userSvc.GetAll().AnyAsync(predicate: m => m.u_name == u_name && m.u_pwd == u_pwd); } }
[HttpGet] public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel lg) { if (ModelState.IsValid) { if (await userManager.Login(lg.u_name, lg.u_pwd)) { //跳转 //是否记住我 if (lg.RememberMe) { Response.Cookies.Add(new HttpCookie(name:"u_name",Server.UrlEncode(lg.u_name)) { Value = lg.u_name, Expires = DateTime.Now.AddDays(7) }); } else { Session["u_name"] = lg.u_name; } return RedirectToAction(nameof(Index)); } else { ModelState.AddModelError(key:"",errorMessage:"您的账号和密码有误"); }; } return View(lg); }
过滤器:
public override void OnAuthorization(AuthorizationContext filterContext) { //base.OnAuthorization(filterContext); if(!(filterContext.HttpContext.Session["u_name"]!=null||filterContext.HttpContext.Request.Cookies["u_name"]!=null)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary() { { "controller","Home"}, { "action","Login"} }); } }
3.遇到的问题:
① 输入用户名和密码登录后需要在主页面显示登录的用户名,cookie对中文编码出现乱码;
② 登录后跳转的首页需要判断角色去显示不同的内容;
4.解决的方案
① 使用cookie的编码和解码对用户名进行封装;
② 在前台界面获取到登录用户的角色id值,在页面中使用if进行判断分别去显示不同的内容;
5.燃尽图