c# - 如何从 ASP.NET Core 中的 ActionFilterAttribute 访问 AppSettings

标签 c# asp.net-core .net-core

我目前正在尝试开发一个 WebAPI (.NET Core),它有一些应该使用 HTTP 基本身份验证的 Controller 操作。为了实现这一点,我编写了一个 ActionFilterAttribute,然后我可以在我的 Controller 中使用它来限制对某些操作的访问。如果我这样做,这一切都很好:

BasicAuthAttribute.cs

public class BasicAuthAttribute : ActionFilterAttribute{
    private string _username { get; set; }
    private string _password { get; set; }

    public BasicAuthAttribute(string username, string password) {
        _username = username;
        _password = password;
    }

    public override void OnActionExecuting(ActionExecutingContext actionContext) {
    //do Auth check...
    }
}

然后在 Controller 中我按如下方式使用它:

SomeController.cs

[BasicAuth("testuser","testpassword")]
[HttpGet("{id}")]
public IActionResult Get(string id) {
    return new ObjectResult("Test");
}

现在我不想在 SomeController.cs 中指定用户名和密码。相反,我想将它们存储在 appsettings.json 中。如何在 ActionFilterAttribute 的 OnActionExecuting 方法中访问存储在 appsettings.json 中的值?

如果我将 BasicAuthAttribute 的构造函数更改为以下内容,.Net 希望我传递设置,这是不可能的。依赖注入(inject)在这里似乎不起作用。

public BasicAuthAttribute(IOptions<AppSettings> appSettings) {}

任何帮助或想法将不胜感激

根据 Set 的回答更新:

我最终将属性更改为过滤器。如果其他人需要它,请参阅下面的工作解决方案:

BasicAuthFilter.cs

public class BasicAuthFilter : IActionFilter {

    protected AppSettings _settings { get; set; }

    public BasicAuthAttribute(IOptions<AppSettings> appSettings) {
        _settings = appSettings;
    }

    public void OnActionExecuted(ActionExecutedContext context) {
        //nothing to do here
    }

    public override void OnActionExecuting(ActionExecutingContext actionContext) 
    {
        //do Auth check...
    }
}

SomeController.cs

public class SomeController : Controller {
   [TypeFilter(typeof(BasicAuthFilter))]
   [HttpGet("{id}")]
   public IActionResult Get(string id) {
        return new ObjectResult("Test");
   }
}   

最佳答案

过滤器部分在 ASP.NET Core documentation解释如何使用 DI:

If your filters have dependencies that you need to access from DI, there are several supported approaches. You can apply your filter to a class or action method using one of the following:

  • ServiceFilterAttribute
  • TypeFilterAttribute
  • IFilterFactory 在您的属性上实现

关于c# - 如何从 ASP.NET Core 中的 ActionFilterAttribute 访问 AppSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423194/

相关文章:

c# - 为什么 Razor UI 类库是作为 .NET Standard 而不是在 .Net core 中构建的

ubuntu - .net core web api访问容器中的文件夹

C# 浏览器缩放

c# - 将项目添加到底层 ObservableCollection 时,递归 TreeView 不保留结构

c# - UWP 应用程序中的 HttpClient 缓存

asp.net-core - 如何获取所有版本的KRE?

asp.net-mvc - 将 OwinADAuthentication 从 .NET Framework 转换为 .NET Core

c# - 如何在.NET Core中使用多个项目创建docker镜像?

c# - 如何解决多个依赖 Web 应用程序时的依赖问题?

c# - 将 float 转换为 UInt32 - 哪个表达式更精确