如何需要整个ASP .NET MVC应用程序中的授权 [英] How require authorization within whole ASP .NET MVC application

查看:106
本文介绍了如何需要整个ASP .NET MVC应用程序中的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建应用程序,其中那些启用登录应该是出于对未登录用户限制旁边的每一个动作。

我要补充 [授权] 每类的标题前标注?喜欢这里:

 命名空间WebApplication2.Controllers {
[授权]
    公共类HomeController的:控制器{
        公众的ActionResult指数(){
            返回查看();
        }        公众的ActionResult关于(){
            ViewBag.Message =你的应用描述页面。            返回查看();
        }        公众的ActionResult联系(){
            ViewBag.Message =您的联系页面。            返回查看();
        }
    }
}

或有一个快捷方式吗?如果我想改变规则之一,尤其是控制器仅作用?


解决方案

最简单的方法是添加授权属性在过滤器配置将其应用到每个控制器。

 公共类一个FilterConfig
{
    公共静态无效RegisterGlobalFilters(GlobalFilterCollection过滤器)
    {
        filters.Add(新HandleErrorAttribute());        //添加此行
        filters.Add(新AuthorizeAttribute());
    }
}

另一种方法是让所有的控制器从基类继承的。这是我经常做的,因为几乎总是一些共享code我所有的控制器可以使用:

  [授权]
公共抽象类BaseSecuredController:控制器
{
    //各种方法可以去这里
}

和现在,而不是从控制器继承,所有的控制器应该继承这个新类:

 公共类MySecureController:BaseSecuredController
{
}

注意:不要忘了,当你需要它是访问非登录用户添加使用AllowAnonymous 属性。

I create application where every action beside those which enable login should be out of limits for not logged user.

Should I add [Authorize] annotation before every class' headline? Like here:

namespace WebApplication2.Controllers {
[Authorize]
    public class HomeController : Controller {




        public ActionResult Index() {
            return View();
        }

        public ActionResult About() {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact() {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

or there is a shortcut for this? What if I want to change rules for one and only action in particular controller?

解决方案

Simplest way is to add Authorize attribute in the filter config to apply it to every controller.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());

        //Add this line
        filters.Add(new AuthorizeAttribute());
    }
}

Another way is to have all of your controllers inheriting from a base class. This is something I do often as there is almost always some shared code that all of my controllers can use:

[Authorize]
public abstract class BaseSecuredController : Controller
{
    //Various methods can go here
}

And now instead of inheriting from Controller, all of your controllers should inherit this new class:

public class MySecureController : BaseSecuredController
{
}

Note: Don't forget to add AllowAnonymous attribute when you need it to be accessible to non-logged in users.

这篇关于如何需要整个ASP .NET MVC应用程序中的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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