How properly inject HttpContext in MVC6(如何在 MVC6 中正确注入 HttpContext)
问题描述
我的 API 中的数据服务层需要 httpcontext 中的请求信息,我阅读了此 问题,他们说我应该使用 ActionContext 而不是 HttpContext.Current(在 MVC6 中停止).
My data service layer in my API required information that are of the request in the httpcontext, I read this question and they said that I should used the ActionContext instead of HttpContext.Current (discontinue in MVC6).
第一种方法是通过覆盖这个方法来设置控制器内部的数据:
The first way is to set the data inside the controller by overriding this method:
public void OnActionExecuting(ActionExecutingContext context)
{
var routeData = context.RouteData;
var httpContext = context.HttpContext;
...
}
或者通过注入服务层来使用DI
Or using DI by injecting into the service layer
public MyService(IContextAccessor<ActionContext> contextAccessor)
{
_httpContext = contextAccessor.Value.HttpContext;
_routeData = contextAccessor.Value.RouteData;
}
但我不确定下面列出的两行代码是否是执行 DI 的正确方法
but I'm not sure with of the both line of code listed below is correct way to do the DI
services.AddTransient<IContextAccessor<ActionContext>,ContextAccessor>();
services.AddTransient<IContextAccessor<ActionContext>>();
当我这样做时,我得到了这个错误.
when I do this I get this error.
尝试激活时无法解析类型Microsoft.AspNet.Mvc.ActionContext"的服务
Unable to resolve service for type 'Microsoft.AspNet.Mvc.ActionContext' while attempting to activate
更新project.json 网络项目
Update project.json web project
"DIMultiTenan.Infrastructure": "",
"DIMultiTenan.MongoImplementation": "",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta3",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta3"
推荐答案
如果你试图访问 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...
这篇关于如何在 MVC6 中正确注入 HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MVC6 中正确注入 HttpContext
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01