asp.net mvc添加到AUTHORIZE属性

如何创建自定义属性以扩展MVC中的现有Authorize属性

解决方法

从AuthorizeAttribute导出你的类.覆盖OnAuthorization方法.添加并设置CacheValidationHandler.
public void CacheValidationHandler( HttpContext context,object data,ref HttpValidationStatus validationStatus )
{
    validationStatus = OnCacheAuthorization( new HttpContextwrapper( context ) );
}


public override void OnAuthorization( AuthorizationContext filterContext )
{
    if (filterContext == null)
    {
        throw new ArgumentNullException( "filterContext" );
    }

    if (AuthorizeCore( filterContext.HttpContext ))
    {
       ... your custom code ...
       SetCachePolicy( filterContext );
    }
    else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
        // auth Failed,redirect to login page
        filterContext.Result = new HttpUnauthorizedResult();
    }
    else
    {
       ... handle a different case than not authenticated
    }
}


protected void SetCachePolicy( AuthorizationContext filterContext )
 {
     // ** IMPORTANT **
     // Since we're performing authorization at the action level,the authorization code runs
     // after the output caching module. In the worst case this Could allow an authorized user
     // to cause the page to be cached,then an unauthorized user would later be served the
     // cached page. We work around this by telling proxies not to cache the sensitive page,// then we hook our custom authorization code into the caching mechanism so that we have
     // the final say on whether a page should be served from the cache.
     HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
     cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
     cachePolicy.AddValidationCallback( CacheValidationHandler,null /* data */);
 }

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....