问题描述
在 ASP.NET MVC 4 及以下我们只需在 Global.asax 中添加以下内容:
In ASP.NET MVC 4 and below we just add the following in Global.asax:
GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });
知道如何在 ASP.NET Core MVC 中执行此操作吗?
Any idea how to do this in ASP.NET Core MVC?
推荐答案
来自 docs:
您可以全局注册过滤器(适用于所有控制器和操作)通过将其添加到 MvcOptions.Filters
集合中Startup
类中的 ConfigureServices
方法:
You can register a filter globally (for all controllers and actions) by adding it to the
MvcOptions.Filters
collection in theConfigureServices
method in theStartup
class:
您不能将 AuthorizeAttribute
添加到 MvcOptions.Filters
中.创建一个 AuthorizationPolicy
并使用 AuthorizeFilter
:
You can not add AuthorizeAttribute
into MvcOptions.Filters
. Create an AuthorizationPolicy
and use AuthorizeFilter
:
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole("Admin", "SuperUser")
.Build();
services.AddMvc(options =>
{
options.Filters.Add(new AuthorizeFilter(policy));
});
这篇关于如何在 ASP.NET Core 中添加全局 `AuthorizeFilter` 或 `AuthorizeAttribute`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!