如何在 MVC6 中正确注入 HttpContext [英] How properly inject HttpContext in MVC6

查看:28
本文介绍了如何在 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 应仅注册为 TransientScoped 而不是 SingletonHttpContext 是基于每个请求的...

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆