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

Gar*_*hPN 1 c# appsettings authorize-attribute iauthorizationfilter asp.net-core-mvc

在我的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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这使我可以用类似的东西装饰控制器方法 [AllowGroups(PermissionGroups.Admin, PermissionGroups.Level1]

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

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

Nko*_*osi 5

在启动时配置设置,

通过选项

services.Configure<MySettings>(Configuration.GetSection("groups"));
Run Code Online (Sandbox Code Playgroud)

或具体对象模型

MySettings settings = Configuration.GetSection("groups").Get<MySettings>();
services.AddSingleton(settings);
Run Code Online (Sandbox Code Playgroud)

然后通过HttpContext.RequestServices过滤器中的

var services = context.HttpContext.RequestServices;

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

//...
Run Code Online (Sandbox Code Playgroud)

虽然采用更多服务定位器方法,但应允许访问所需的配置。

  • @GarethPN `GetSrvice&lt;T&gt;` 是一种扩展方法。您很可能缺少用于依赖注入的 `using` 命名空间。 (2认同)
  • 啊哈!我添加了“使用Microsoft.Extensions.DependencyInjection;”来访问解决了我的错误的通用方法。谢谢您的帮助 :) (2认同)