在我的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]
我打算做的是根据列出的枚举值从appsettings.json中检索组名,并检查用户是否是这些组的成员。
我的问题是,从属性类中访问应用程序设置的正确方法是什么?
答案 0 :(得分:5)
在启动时配置设置,
通过选项
services.Configure<MySettings>(Configuration.GetSection("groups"));
或具体对象模型
MySettings settings = Configuration.GetSection("groups").Get<MySettings>();
services.AddSingleton(settings);
然后通过过滤器中的HttpContext.RequestServices
对其进行解析
var services = context.HttpContext.RequestServices;
var settings = services.GetService<MySettings>();
//-- OR --
//var settings = services.GetService<IOptions<MySettings>>().Value;
//...
采用更多服务定位器方法时,应允许访问所需的配置。