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

时间:2018-10-24 12:15:38

标签: c# asp.net-core-mvc appsettings authorize-attribute iauthorizationfilter

在我的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中检索组名,并检查用户是否是这些组的成员。

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

1 个答案:

答案 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;

//...

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