Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Request's header in services.AddScoped in WebApi Core ConfigureServices?

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?

like image 616
Mohammad Dayyan Avatar asked Nov 29 '17 09:11

Mohammad Dayyan


1 Answers

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"];
});
like image 122
SpruceMoose Avatar answered Oct 17 '22 07:10

SpruceMoose