什么是保护从控制器的所有动作除了一个(登录)的最佳方法是什么? [英] What's the best way to protect all actions from a Controller except one (Login)?

查看:123
本文介绍了什么是保护从控制器的所有动作除了一个(登录)的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有 [授权] 属性在所有对我的 AdminController 的方法除了登录操作。

Currently I have [Authorize] attributes on all of the methods on my AdminController except for the Logon action.

什么是洁净的方式来颠倒这一点,所以我没有记住的属性添加到所有的方法,而是添加属性只是方法(县),应提供没有被登录?

What's the cleanest way to invert this, so I don't have to remember to add the attributes to all methods, but rather add an attribute only to the method(s) that should be available without being logged in?

我会更好,只是移动登录行动,自己的控制器,并运用 [授权] 属性到AdminController类?

Would I be better just moving the Logon action to its own controller, and applying the [Authorize] attribute to the AdminController class?

推荐答案

在ASP.NET MVC 3,你可以实现一个自定义全局的动作过滤器提供商

In ASP.NET MVC 3 you could implement a custom global action filter provider:

public class MyProvider : IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var rd = controllerContext.RouteData;
        var controller = rd.GetRequiredString("controller");
        if (string.Equals("admin", controller, StringComparison.OrdinalIgnoreCase) &&
            string.Equals("logon", actionDescriptor.ActionName))
        {
            return Enumerable.Empty<Filter>();
        }

        return new[]
        {
            new Filter(new AuthorizeAttribute(), FilterScope.Action, 0)
        };
    }
}

这可能在的Application_Start 进行注册:

FilterProviders.Providers.Add(new MyProvider());

现在,如果你使用的是一些DI容器,如NInject例如,它支持<一个href="http://stackoverflow.com/questions/6364047/how-to-use-ninject-to-inject-services-into-an-authorization-filter/6364134#6364134">filter绑定语法这意味着你可以配置内核基于上下文动态地注入过滤器。

Now if you are using some DI container such as NInject for example it supports filter binding syntax meaning that you could configure the kernel to inject the filter dynamically based on the context.

这种方法的优点是,现在nomatter什么控制器或动作被添加到您的应用程序=>这将需要授权。

The pros of this approach is that now nomatter what controller or action is being added to your application => it will require authorization.

这篇关于什么是保护从控制器的所有动作除了一个(登录)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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