[英]ASP.NET Core controller constructor: access request information
I have a base controller class with ILog log
field, which is set at constructor from custom logger service, passed via dependency injection. 我有一个带有
ILog log
字段的基本控制器类,该字段是通过自定义记录器服务在构造函数中设置的,并通过依赖项注入传递。
I'd like to access something like request context in controller constructor to get arbitrary HTTP header or HttpContext.Items
or something like that to use it when creating my log
. 我想访问控制器构造函数中的请求上下文之类的东西,以获取任意的HTTP标头或
HttpContext.Items
或类似的东西在创建log
时使用它。
I tried using IHttpContextAccessor
. 我尝试使用
IHttpContextAccessor
。 It gives me DefaultHttpContext
which does not contain Items
added by middleware. 它为我提供了
DefaultHttpContext
,它不包含中间件添加的Items
。
The only thing that i can imagine is to make log
property of controller public
and write an IActionFilter
which sets this property. 我唯一能想到的就是
public
控制器的log
属性,并编写一个设置该属性的IActionFilter
。 Because action filters have access to both context and controller instance. 因为操作过滤器可以访问上下文和控制器实例。
Not having request context in controller constructor looks weird to me, because request information can be useful to avoid boilerplate code in actions. 在控制器构造函数中没有请求上下文对我来说很奇怪,因为请求信息对于避免动作中的样板代码很有用。 Controllers are created per request anyway, so there's no harm to use some request data in constructor.
无论如何,控制器都是针对每个请求创建的,因此在构造函数中使用一些请求数据不会造成任何危害。
For request level logging use an ActionFilter
attrbute and inject an ILogger
to that. 对于请求级别的日志记录,请使用
ActionFilter
属性并向其中注入ILogger
。 I'm not sure but I think in MVC 5+ the dependency injection is supported in action filter attributes. 我不确定,但是我认为在MVC 5+中,动作过滤器属性支持依赖项注入。 If not, instead of registering in
GlobalFilters
, you can implement an IFilterProvider
for attaching and instantiating the attribute to the requests you'd like to. 如果不是,则可以实现
IFilterProvider
来代替在GlobalFilters
中注册,以将属性附加和实例化到您想要的请求。
On the other hand, if you need any kind of business level logging (so for example inside an action body), use the injected ILogger
in the controller, but then you should not call any logging logic until the process is inside an action. 另一方面,如果您需要任何类型的业务级别日志记录(例如在操作主体内部),请在控制器中使用注入的
ILogger
,但是在流程位于操作内部之前,您不应调用任何日志记录逻辑。 At that point you'll already have a built-up request context. 届时,您将已经拥有一个构建请求上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.