gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:43:36 24 4
gpt4 key购买 nike

我目前正在尝试开发一个 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/

24 4 0
文章推荐: c# - Dictionary> 是否符合半持久性?
文章推荐: C++ : discards qualifier even if the member variables are mutable
文章推荐: c++ - Mac 上 C++ 中 for 循环的奇怪行为
文章推荐: c# - 将 CookComputing XMLRpcStruct (IEnumerable) 转换为实际的 C# 类