当前位置:  开发笔记 > 编程语言 > 正文

asp.net mvc添加到AUTHORIZE属性

如何解决《asp.netmvc添加到AUTHORIZE属性》经验,为你挑选了2个好方法。

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



1> tvanfosson..:

从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 */);
 }



2> Mike Chaliy..:

您不需要扩展此属性,web.config就足够了.请阅读有关表单元素的身份验证.请注意defaultUrl.这就是你需要的东西.


  
    
  


嗯,为什么不在一个人提出解决方案之前指定所有要求?
推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有