如何在控制器中注入HttpHeader值? [英] How to inject HttpHeader value in controller?
问题描述
我有使用ASP.NET Core API开发的Web API.每个传入请求都插入了一个自定义标头值.例如x-correlationid
.控制器使用该值记录和跟踪请求.
目前,我正在如下读取每个控制器中的值
I have Web API developed using ASP.NET Core API. Every incoming request has a custom header value inserted. eg x-correlationid
. The controller use this value for logging and tracing the request.
Currently I'm reading the value in each controller as below
[Route("api/[controller]")]
public class DocumentController : Controller
{
private ILogger<TransformController> _logger;
private string _correlationid = null;
public DocumentController(ILogger<DocumentController > logger)
{
_logger = logger;
_correlationid = HttpContext.Request.Headers["x-correlationid"];
}
[HttpPost]
public async Task<intTransform([FromBody]RequestWrapper request)
{
_logger.LogInformation("Start task. CorrelationId:{0}", _correlationid);
// do something here
_logger.LogInformation("End task. CorrelationId:{0}", _correlationid);
return result;
}
}
我认为这违反了DI规则.
I think this is against DI rules.
我希望将值注入控制器的构造函数中,而不是读取控制器的构造函数中的值.
或
中间件能否读取x-correlationid
和*somehow*
使其对所有控制器可用,所以我们不必将其注入任何控制器中?
Instead of reading the value inside the controller's constructor, I want to inject the value in the controller's constructor.
Or
Can middleware read the x-correlationid
and *somehow*
make it available to all the controllers so we don't have to inject it in any controller?
这里有什么更好的选择?
What would be a better option here?
推荐答案
这是我想到的.我想我也可以对其进行单元测试.
This is what I came up with. I think i can also unit test it.
public interface IRequestContext
{
string CorrelationId { get; }
}
public sealed class RequestContextAdapter : IRequestContext
{
private readonly IHttpContextAccessor _accessor;
public RequestContextAdapter(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
public string CorrelationId
{
get
{
return this._accessor.HttpContext.Request.Headers[Constants.CORRELATIONID_KEY];
}
}
}
然后在启动程序的configureservice方法中注册适配器
then in startup's configureservice method register the adapter
services.AddSingleton<IRequestContext, RequestContextAdapter>();
并将其注入控制器
[Route("api/[controller]")]
public class DocumentController : Controller
{
private ILogger<TransformController> _logger;
private IRequestContext _requestContext = null;
public DocumentController(ILogger<DocumentController > logger,IRequestContext requestContext)
{
_logger = logger;
_requestContext = requestContext;
}
[HttpPost]
public async Task<intTransform([FromBody]RequestWrapper request)
{
_logger.LogInformation("Start task. CorrelationId:{0}", _requestContext.CorrelationId);
// do something here
_logger.LogInformation("End task. CorrelationId:{0}", _requestContext.CorrelationId);
return result;
}
}
这篇关于如何在控制器中注入HttpHeader值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!