Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET core web API – how can I register a value derived from the request context?

In ASP.NET core web API, I’d like to define an endpoint like this (example):

app.MapGet("userId", (User user) => user.id);

In this example, the endpoint exposed to the caller should take no parameters. The User object should be derived from information present in the request (e.g. in the header), but the method definition shouldn’t need to know that detail – it should just be able to access User as a dependency.

I thought that I could accomplish this by specifying a resolution for the User dependency similar to this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

builder.Services.AddScoped(typeof(User), p =>
{
    var cont = p.GetService<HttpContext>();    
    return new User(cont.Request.Headers["userKey"].ToString());
});

However, when I run this, the p.GetService<HttpContext>() returns null.

How can I create a request-scoped dependency resolution that incorporates data from the request? Is this a good approach, but I’m just not looking for the right service? Or is this approach not going to work?

>Solution :

Try using the HttpContextAccessor

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(typeof(User), p =>
{
  var httpContextAccessor = p.GetService<IHttpContextAccessor>();
  var httpContext = httpContextAccessor.HttpContext;
  (...)
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading