ASP.NET Core Web API: 我如何注册从请求上下文派生的值?

huangapple go评论50阅读模式
英文:

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(&quot;userId&quot;, (User user) =&gt; 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 =&gt;
{
    var cont = p.GetService&lt;HttpContext&gt;();    
    return new User(cont.Request.Headers[&quot;userKey&quot;].ToString());
});

However, when I run this, the p.GetService&lt;HttpContext&gt;() 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 =&gt;
{
  var httpContextAccessor = p.GetService&lt;IHttpContextAccessor&gt;();
  var httpContext = httpContextAccessor.HttpContext;
  (...)
});

huangapple
  • 本文由 发表于 2023年2月16日 03:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定