創建一個全球性的授權過濾器 -
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// do Authorization
}
}
然後在Global.asax中註冊了 -
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyAuthorizationFilterAttribute());
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
雖然你可以創建一個定製的認證模塊 -
public class CustomAuthentication : IHttpModule
{
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(this.Authenticate);
}
public void Authenticate(object source, EventArgs eventArgs)
{
HttpApplication _application = (HttpApplication)source;
HttpContext _context = _application.Context;
// do authentication
// if authenticated set pricipal
// _context.User = new GenericPrincipal(new GenericIdentity("user"), new string[]);
}
public void Dispose() { }
}
然後你只需要在web.config中註冊模塊
<modules runAllManagedModulesForAllRequests="true">
<add name="CustomAuthentication" type="AuthenticationNamespace.CustomAuthentication"/>
</modules>
,並設置asp.net身份驗證沒有 -
<authentication mode="None">
</authentication>
然後,你可以檢查它的用戶在你的AuthorizationFilter進行身份驗證。
if(HttpContext.Current.Request.User.Identity.IsAuthenticated)