如何添加AuthorizeAttribute全球水平,排除了一些行动? [英] How to add AuthorizeAttribute on global level and exclude it for some Actions?

查看:293
本文介绍了如何添加AuthorizeAttribute全球水平,排除了一些行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查,如果一个动作有特定属性,我需要做的是在下面的方法:

I need to check if an action have specific attribute, and I need do it in the following method :

protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {

}

我知道我可以在这里检查一下:

I know I can Check it here:

public override void OnAuthorization(AuthorizationContext filterContext) {

    filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true)
 ...
}

是否有任何人知道我怎样才能获得 ActionDescriptor System.Web.HttpContextBase 对象?

更新

其实我想如果任何标记 AnonymousAllowedAttribute AuthorizeCore 方法返回true或如果有可能动作不跑(我的意思是我的重写方法)。

Actually I want if any of actions marked with AnonymousAllowedAttribute the AuthorizeCore method return true or if possible don't run (I mean my override method).

推荐答案

要做到你想要什么,你需要编写并在Global.asax中注册新FilterProvider。
例如:

To do what you want you need to write and register new FilterProvider in your global.asax. Example:

public class AuthorizeFilterProvider:IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (!actionDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true))
            return new Filter[] {new Filter(new AuthorizeAttribute(), FilterScope.Action, 0), };
        return new Filter[0];
    }
}

Global.asax的:

global.asax:

protected void Application_Start()
    {
        ....
        RegsterFilterProviders(FilterProviders.Providers);
    }

    private void RegsterFilterProviders(FilterProviderCollection providers)
    {
        providers.Add(new AuthorizeFilterProvider());
    }

现在,如果你的任何行动没有标记 [AnonymousAllowed] 应用程序认为这是标记为 [授权]

PS:不要忘记标记 [AnonymousAllowed] 您的登录和注册动作:)

Now if any of your action is not marked [AnonymousAllowed] application think that it is marked as [Authorize]
PS: Don't forget to mark [AnonymousAllowed] your log on and register actions :)

这篇关于如何添加AuthorizeAttribute全球水平,排除了一些行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆