gpt4 book ai didi

c# - 如何在 .Net Core 的 AuthorizeAttribute 类中访问 appsetting.json 参数

转载 作者:行者123 更新时间:2023-12-03 19:09:30 25 4
gpt4 key购买 nike

在我的 ASP.NET Core MVC 应用程序中,我有一个继承自 AuthorizeAttribute 并实现 IAuthorizationFilter 的类。

namespace MyProject.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AllowGroupsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly List<PermissionGroups> groupList = null;
public AllowGroupsAttribute(params PermissionGroups[] groups)
{
groupList = groups.ToList();
}

public void OnAuthorization(AuthorizationFilterContext context)
{
var executingUser = context.HttpContext.User;

//If the user is not authenticated then prevent execution
if (!executingUser.Identity.IsAuthenticated)
{
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
}
}
}

这让我可以用 [AllowGroups(PermissionGroups.Admin, PermissionGroups.Level1] 之类的东西来装饰 Controller 方法。

我打算做的是根据列出的枚举值从 appsettings.json 检索组名,并检查用户是否是这些组的成员。

我的问题是,从我的属性类中访问应用程序设置的正确方法是什么?

最佳答案

在启动时配置设置,
通过选项

services.Configure<MySettings>(Configuration.GetSection("groups"));
或具体的对象模型
MySettings settings = Configuration.GetSection("groups").Get<MySettings>();
services.AddSingleton(settings);
然后通过 HttpContext.RequestServices 解决它们过滤器内
//...

IServiceProvider services = context.HttpContext.RequestServices;

MySettings settings = services.GetService<MySettings>();
//-- OR --
//MySettings settings = services.GetService<IOptions<MySettings>>().Value;

//...
虽然是一种更多的服务定位器方法,但它应该允许访问所需的配置。

关于c# - 如何在 .Net Core 的 AuthorizeAttribute 类中访问 appsetting.json 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52968783/

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