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
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01