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
Middleware vs Filters Filters are a part of MVC, so they are scoped entirely to the MVC middleware. Middleware only has access to the HttpContext and anything added by preceding middleware. In contrast, filters have access to the wider MVC context, so can access routing data and model binding information for example.
Filters in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline. Built-in filters handle tasks such as: Authorization, preventing access to resources a user isn't authorized for. Response caching, short-circuiting the request pipeline to return a cached response.
Filters run in the following order: Authorization filters. Action filters. Response filters.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With