How do I get Configuration, Cookie and DBContext in Action Filter in ASP.Net Core 2.x

Viewed 3164

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.

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

2 Answers

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);
    }
}

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);
}

For using ActionFilter in controller action.

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

For accessing Configuration from ActionFilter Try code below :

    private IConfiguration configuration;

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
        var connString = configuration["ConnectionStrings"];
    }
Related