
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所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)