英文:
ASP.NET Core Web API: how can I register a value derived from the request context?
问题
在ASP.NET Core Web API中,我想定义一个类似以下示例的端点:
app.MapGet("userId", (User user) => user.id);
在这个示例中,对调用者公开的端点不应该接受任何参数。User
对象应该从请求中的信息(例如,在标头中)派生,但方法定义不需要知道这个细节 - 它应该只能访问User
作为依赖项。
我认为可以通过类似于以下方式指定User
依赖项的解析来实现这一点:
builder.Services.AddScoped(typeof(User), p =>
{
var cont = p.GetService<HttpContext>();
return new User(cont.Request.Headers["userKey"].ToString());
});
然而,当我运行这段代码时,p.GetService<HttpContext>()
返回 null
。
如何创建一个包含来自请求数据的请求范围依赖解析?这是一个好方法吗,只是我没有找到正确的服务吗?还是这种方法不会奏效?
英文:
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?
答案1
得分: 2
试试使用HttpContextAccessor
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(typeof(User), p =>
{
var httpContextAccessor = p.GetService<IHttpContextAccessor>();
var httpContext = httpContextAccessor.HttpContext;
(...)
});
英文:
Try using the HttpContextAccessor
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(typeof(User), p =>
{
var httpContextAccessor = p.GetService<IHttpContextAccessor>();
var httpContext = httpContextAccessor.HttpContext;
(...)
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论