如何在ASP.Net Core 2.x的操作筛选器中获取配置,Cookie和DBContext [英] How do I get Configuration, Cookie and DBContext in Action Filter in ASP.Net Core 2.x

查看:35
本文介绍了如何在ASP.Net Core 2.x的操作筛选器中获取配置,Cookie和DBContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示.如何使用ASP.NET Core 2.x在同一操作筛选器中访问IConfiguration,Cookie和DBContext?

As the title suggests. How do I access IConfiguration, Cookies and my DBContext in the same action filter using ASP.NET Core 2.x?

我可以找到许多建议如何做一个或另一个的文章,但我什至找不到两个可以做的事,更不用说三个了.

I can find many articles that suggest how to do one or the other but I can't find anything to do even two let alone all three.

当我尝试合并文章时,通常会遇到一个或多个运行时错误.

When I try to combine the articles I usually get one or more runtime errors.

有没有办法做到这一点.我有一个非常有用的库,我正在尝试从ASP.Net移植过来,我真的不想重写所有内容.

Is there a way to do this. I have a really useful library I am trying t port over from ASP.Net and I don't really want to rewrite it all.

任何帮助或工作示例将不胜感激.谢谢

Any help or working examples would be very much appreciated. Thanks

推荐答案

要从ActionFilter构造函数访问服务,请尝试以下代码:

For accessing services from ActionFilter constructor, try code below:

public class RequestLoggerActionFilter : ActionFilterAttribute
{
    private readonly ILogger _logger;
    private readonly IConfiguration _configuration;
    private readonly MVCProContext _context;
    private readonly IHttpContextAccessor _httpContextAccessor;
    public RequestLoggerActionFilter(ILoggerFactory loggerFactory
        , IConfiguration configuration
        , MVCProContext context
        , IHttpContextAccessor httpContextAccessor)
    {
        _logger = loggerFactory.CreateLogger("RequestLogger");
        _configuration = configuration;
        _context = context;
        _httpContextAccessor = httpContextAccessor;
        var cookies = _httpContextAccessor.HttpContext.Request.Cookies;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {           
        base.OnActionExecuting(context);
    }
}

如果要在 OnActionExecuting 中访问而无需构造函数注入.

If you want to access in OnActionExecuting without constructor injection.

public override void OnActionExecuting(ActionExecutingContext context)
{
    var configuration = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
    var cookies = context.HttpContext.Request.Cookies;
    var db = context.HttpContext.RequestServices.GetRequiredService<MVCProContext>();
    base.OnActionExecuting(context);
}

用于在控制器操作中使用 ActionFilter .

For using ActionFilter in controller action.

[TypeFilter(typeof(RequestLoggerActionFilter))]
public ActionResult RequestLogger()
{
    return Ok("RequestLoggerActionFilter");
}

这篇关于如何在ASP.Net Core 2.x的操作筛选器中获取配置,Cookie和DBContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆