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

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

问题描述

我创建了应用程序,其中除了启用登录的操作之外的所有操作都应该超出未登录用户的限制.

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

我是否应该在每个类的标题前添加[Authorize] 注释?喜欢这里:

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?

推荐答案

最简单的方法是在过滤器配置中添加 Authorize 属性以将其应用到每个控制器.

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
}

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

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

public class MySecureController : BaseSecuredController
{
}

注意:不要忘记添加 AllowAnonymous 属性,以便非登录用户可以访问它.

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天全站免登陆