I've got some question about accessing HttpContext from DI Container for .NET Core (I am using .NET 6 to be specific). My purpose is to get request header e.g. CorrelationId. Here is my DI Container code.
services.AddControllers()
.ConfigureApiBehaviorOptions(o =>
{
o.InvalidModelStateResponseFactory = c =>
{
var keys = c.ModelState.Where(l => l.Value.Errors.Count > 0).Select(k => k.Key).ToList();
string error = string.Empty;
if (keys != null)
{
error = keys.Count <= 1 ? keys[0] : keys[1];
error = error.Replace("$.", string.Empty);
}
error = $"Field: {error}. Message: {c.ModelState.Values.ElementAt(0).Errors[0].ErrorMessage}";
//GET REQUEST HEADER
//string correlationId = retrieve correlationId from request header
Response response = new();
response.Fail(correlatinId, error);
return new BadRequestObjectResult(response);
};
})
.AddFluentValidation(o =>
{
o.ImplicitlyValidateChildProperties = true;
o.ImplicitlyValidateRootCollectionElements = true;
o.RegisterValidatorsFromAssemblyContaining<LogErrorValidation>();
});
The purpose of my code snippet is to override Bad Request response model with custom response model since I am using Fluent Validation. My custom response model consist of correlationId (GUID) and message (string).
Is it possible to retrieve request header from DI container?
Thank you.