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:
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;
(...)
});