更新时间:2023-02-24 11:39:44
如果你试图访问 HttpContext
,那么你可以使用 IHttpContextAccessor
来达到这个目的.
If you are trying to access HttpContext
, then you can use IHttpContextAccessor
for this purpose.
例子:
services.AddTransient<QueryValueService>();
public class QueryValueService
{
private readonly IHttpContextAccessor _accessor;
public QueryValueService(IHttpContextAccessor httpContextAccessor)
{
_accessor = httpContextAccessor;
}
public string GetValue()
{
return _accessor.HttpContext.Request.Query["value"];
}
}
请注意,在上面的示例中,QueryValueService
应仅注册为 Transient
或 Scoped
而不是 Singleton
HttpContext 是基于每个请求的...
Note that in the above example QueryValueService
should be registered only as Transient
or Scoped
and not Singleton
as HttpContext is per-request based...