[英]How do I get Configuration, Cookie and DBContext in Action Filter in ASP.Net Core 2.x
As the title suggests. 如标题所示。 How do I access IConfiguration, Cookies and my DBContext in the same action filter using ASP.NET Core 2.x? 如何使用ASP.NET Core 2.x在同一操作筛选器中访问IConfiguration,Cookie和DBContext?
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. 我有一个非常有用的库,我正在尝试从ASP.Net移植过来,我真的不想重写所有内容。
Any help or working examples would be very much appreciated. 任何帮助或工作示例将不胜感激。 Thanks 谢谢
For accessing services from ActionFilter constructor, try code below: 要从ActionFilter构造函数访问服务,请尝试以下代码:
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. 如果要在OnActionExecuting
访问而无需构造函数注入。
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. 用于在控制器动作中使用ActionFilter
。
[TypeFilter(typeof(RequestLoggerActionFilter))]
public ActionResult RequestLogger()
{
return Ok("RequestLoggerActionFilter");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.