web api 登陆错误登陆界面
1 <authentication mode="Forms"> 2 <forms loginUrl="~/Account/Login" timeout="2880" /> 3 </authentication>
自定义Authorize
因为需要实时添加角色,所以自定义,只需要重写AuthorizeCore和OnAuthorization
public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { public new string[] Roles { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("HttpContext"); } if (!httpContext.User.Identity.IsAuthenticated) { return false; } if (Roles == null) { return true; } if (Roles.Length == 0) { return true; } if (Roles.Any(httpContext.User.IsInRole)) { return true; } return false; } public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionDescriptor.ActionName; string roles = GetRoles.GetActionRoles(actionName, controllerName); if (!string.IsNullOrWhiteSpace(roles)) { this.Roles = roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); } base.OnAuthorization(filterContext); } }
MVC的过滤器是根据c# 的特性发展的下面说下c# 的特性
作用:为类型方法属性声明信息,可以通过反射获取,orm映射也用到了特性
定位参数:为自定义特性类的构造函数的参数(可以有多个构造函数)
public class MyAttribute : Attribute { public MyAttribute(string url) { } public MyAttribute(string url,string name) { } } [MyAttribute("www.baidu.com","xiaoli")] public class Instancevariable { public Instancevariable(string cls) { Console.WriteLine(cls); } }
命名参数:写法参数名=参数值 可读写
多个特性逗号分开
介绍下修饰特性的元特性 [AttributeUsage(AttributeTargets.Class,AllowMutiple=false,Inherited=false)]
1 AttributeTargets.Class:特性的作用对象
2 AllowMutiple:可否在程序中存在多个性的实例
3Inherited:为false 类 ClassA应用了特性F,ClassB继承ClassA ,ClassB是没特性F的