加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:05:24 所属栏目:百科 来源:网络整理
导读:我目前正在尝试开发一个WebAPI(.NET Core),它具有一些应该使用HTTP基本身份验证的控制器操作.为了实现这一点,我编写了一个ActionFilterAttribute,然后我可以在我的控制器中使用它来限制对某些操作的访问.如果我做这样的事情,这一切都很好: BasicAuthAttribu
我目前正在尝试开发一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读