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


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01