【问题标题】:How do you access appsetting.json parameters in an AuthorizeAttribute class in .Net Core如何在 .Net Core 的 AuthorizeAttribute 类中访问 appsetting.json 参数
【发布时间】:2019-03-28 20:33:21
【问题描述】:

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

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

【问题讨论】:

  • 在启动时通过选项或具体对象模型配置设置,然后通过HttpContext.RequestServices解决它们

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


【解决方案1】:

在启动时配置设置,

通过选项

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;

//...

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

【讨论】:

  • 谢谢。我想我现在更接近实现这个了,我已经实现了一个带有字典的类来从设置中提取该部分,那里没有错误。但是我在var settings = services.GetService&lt;MySettings&gt;(); 线上有一个构建错误。错误读取 CS0308 The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments
  • @GarethPN GetSrvice&lt;T&gt; 是一种扩展方法。您很可能缺少用于依赖注入的 using 名称空间。
  • 啊哈!我添加了using Microsoft.Extensions.DependencyInjection; 以访问解决我的错误的通用方法。谢谢你的帮助:)
【解决方案2】:

我遇到了同样的问题,你解决了

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AllowGroupsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();
            var user = configuration.GetSection("AppConfig").GetSection("user").Value;
            var pass = configuration.GetSection("AppConfig").GetSection("pass").Value;

..........

}

在 appsettings.json 中

"AppConfig": {
    "user": "hola",
    "pass": "mundo"
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多