gpt4 book ai didi

c# - 如何在 ASP.NET Core 中添加全局 `AuthorizeFilter` 或 `AuthorizeAttribute`?

转载 作者:行者123 更新时间:2023-12-02 23:44:31 25 4
gpt4 key购买 nike

ASP.NET MVC 4 及以下版本中,我们只需在 Global.asax 中添加以下内容:

GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });

知道如何在 ASP.NET Core MVC 中执行此操作吗?

最佳答案

来自docs :

You can register a filter globally (for all controllers and actions) by adding it to the MvcOptions.Filters collection in the ConfigureServices method in the Startup class:

您无法将 AuthorizeAttribute 添加到 MvcOptions.Filters 中。创建 AuthorizationPolicy 并使用 AuthorizeFilter:

var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole("Admin", "SuperUser")
.Build();

services.AddMvc(options =>
{
options.Filters.Add(new AuthorizeFilter(policy));
});

关于c# - 如何在 ASP.NET Core 中添加全局 `AuthorizeFilter` 或 `AuthorizeAttribute`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41972518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com