public class MyAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { public new string[] Roles { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { bool result = false; if (httpContext == null) { throw new ArgumentNullException("HttpContext"); } if (!httpContext.User.Identity.IsAuthenticated) { } if (Roles != null && Roles.Any(httpContext.User.IsInRole)) { result = true; } if (!result) { httpContext.Response.StatusCode = 403; } return result; } public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionDescriptor.ActionName; string roles = GetActionRoles(actionName, controllerName); if (!string.IsNullOrWhiteSpace(roles)) { this.Roles = roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); } base.OnAuthorization(filterContext); if (filterContext.HttpContext.Response.StatusCode == 403) { filterContext.Result = new RedirectResult("http://www.baidu.com/"); } } private string GetActionRoles(string action, string controller) { XElement rootElement = XElement.Load(HttpContext.Current.Server.MapPath("/") + "ActionRoles.xml"); XElement controllerElement = FindElementByAttribute(rootElement, "Controller", controller); if (controllerElement != null) { XElement actionElement = FindElementByAttribute(controllerElement, "Action", action); if (actionElement != null) { return actionElement.Value; } } return ""; } private XElement FindElementByAttribute(XElement xElement, string tagName, string attribute) { return xElement.Elements(tagName).FirstOrDefault(x => x.Attribute("name").Value.Equals(attribute, StringComparison.OrdinalIgnoreCase)); } }
<?xml version="1.0" encoding="utf-8" ?> <Roles> <Controller name="Home"> <Action name="Index"></Action> <Action name="About">user</Action> <Action name="Contact">admin</Action> <Action name="Tips">admin</Action> </Controller> </Roles>
用WebSecurity认证方式,相当于普通方式将登陆信息保存在session里。
时间: 2024-10-11 17:49:05