授权滤器执行你的授权策略,以确保动作方法只被已认证用户调用。授权过滤器实现 IAuthorizationFilter 接口
1 2 3 4 5 6
| <system.web> <authentication mode="Forms"> <forms timeout="2880"></forms> </authentication> </system.web>
|
登录代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public bool Login(string Account_Name, string Account_Password) { if(Account_Name == "Admin" && Account_Password == "Password") { FormsAuthentication.SetAuthCookie(Account_Name, true); Session["Account_Name"] = Account_Name;
return true; } else { return false } }
|
自定义授权过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class CustomAuthAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (HttpContext.Current.Session["Account_Name"] == null) { HttpCookie httpCookie = new HttpCookie("expired", DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.ffff"));
string area = httpContext.Request.RequestContext.RouteData.DataTokens.FirstOrDefault(m => m.Key == "area").Value?.ToString();
httpCookie.Path = "/" + area;
httpContext.Response.SetCookie(httpCookie); return false; } else { httpContext.Response.SetCookie(new HttpCookie("expired", null)); }
string user = httpContext.User.Identity.Name; if (user == null || user == "") { return false; } else { return true; } }
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { string area = filterContext.RouteData.DataTokens.FirstOrDefault(m => m.Key == "area").Value?.ToString();
if (area == null || area == "") { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Login"}, { "action", "Index"}, }); } else if (area == "Admin") { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "area", area}, { "controller", "Login"}, { "action", "Index"}, }); } } }
|
使用自定义授权过滤器
1 2 3 4 5 6 7 8
| [CustomAuth] public class HomeController { public ActionResult Index() { return View(); } }
|