正如标题所示。如何使用ASP.NET Core 2.x在同一操作筛选器中访问IConfiguration,Cookie和DBContext?
我可以找到许多建议如何做另一种方法的文章,但是我什至找不到任何事情可以做两个,更不用说全部三个了。
当我尝试合并文章时,通常会遇到一个或多个运行时错误。
有没有办法做到这一点。我有一个非常有用的库,我正在尝试从ASP.Net移植过来,我真的不想全部重写。
任何帮助或工作示例将不胜感激。谢谢
答案 0 :(得分:1)
要从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);
}
}
如果要在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);
}
用于在控制器操作中使用ActionFilter
。
[TypeFilter(typeof(RequestLoggerActionFilter))]
public ActionResult RequestLogger()
{
return Ok("RequestLoggerActionFilter");
}
答案 1 :(得分:0)
要从 ActionFilter 访问配置,请尝试以下代码:
private IConfiguration configuration;
public override void OnResultExecuting(ResultExecutingContext context)
{
configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
var connString = configuration["ConnectionStrings"];
}