I want to assign a value to a class instance from Request's header to each request as singleton.
I wanted to assign it with .net core in ConfigureServices
method in Startup
class.
Something like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<MyClass>(provider =>
{
var myClass = new MyClass();
myClass.PropName = provider.Request.Headers["PropName"]; // I want to access Request Header here
});
}
How can I access Request's header in AddScoped
method?
The cleanest approach is to change your MyClass
Constructor as follows:
public MyClass(IHttpContextAccessor httpContextAccessor)
{
this.PropName = httpContextAccessor.HttpContext?.Request?.Headers["PropName"]
}
Then in your DI setup:
services.AddScoped<MyClass>();
Alternatively, if you really need to access this in your DI setup, you can amend as follows:
services.AddScoped<MyClass>(provider =>
{
var myClass = new MyClass();
myClass.PropName = provider.GetService<IHttpContextAccessor>()?.HttpContext?.Request?.Headers["PropName"];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With