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

c# – 如何从ASP.NET Core中的ActionFilterAttribute访问AppSettings,第1张

概述我目前正在尝试开发一个WebAPI(.NET Core),它具有一些应该使用HTTP基本身份验证的控制器 *** 作.为了实现这一点,我编写了一个ActionFilterAttribute,然后我可以在我的控制器中使用它来限制对某些 *** 作的访问.如果我做这样的事情,这一切都很好: BasicAuthAttribute.cs public class BasicAuthAttribute : ActionFi 我目前正在尝试开发一个WebAPI(.NET Core),它具有一些应该使用http基本身份验证的控制器 *** 作.为了实现这一点,我编写了一个ActionFilterattribute,然后我可以在我的控制器中使用它来限制对某些 *** 作的访问.如果我做这样的事情,这一切都很好:

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...    }}

在控制器中,我然后使用它如下:

SomeController.cs

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

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

如果我将BasicAuthAttribute的构造函数更改为以下内容,.Net希望我传递设置,这是不可能的.依赖注入似乎不适用于此.

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全部内容,希望文章能够帮你解决c# – 如何从ASP.NET Core中的ActionFilterAttribute访问AppSettings所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1239591.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存