asp.net mvc 添加到 AUTHORIZE 属性

asp.net mvc Adding to the AUTHORIZE attribute(asp.net mvc 添加到 AUTHORIZE 属性)
本文介绍了asp.net mvc 添加到 AUTHORIZE 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I create a custom attribute to extend existing Authorize attribute in MVC?

推荐答案

从 AuthorizeAttribute 派生你的类.覆盖 OnAuthorization 方法.添加并设置一个 CacheValidationHandler.

Derive your class from AuthorizeAttribute. Override the OnAuthorization method. Add and set up a 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 */);
 }

这篇关于asp.net mvc 添加到 AUTHORIZE 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)