首页 > 解决方案 > Asp.Net Core 2.x HttpContext.Current 不可用

问题描述

我没有看到太多关于将 asp.net mvc 4.6 应用程序移植到 1.0 到 2.0 和 2.0 的 asp.net core 2.1 Tons 的信息。到了2.1的文章,但是变化有点陡峭。

好的,我一直在使用 google 和 stackoverflow,而我正在尝试/想要做的是将旧的 .net 应用程序转换为 .net 核心。

我认为问题的一些大罪魁祸首如下:

HttpContext.Current
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)
private static string CollectionToHtmlTable(HttpCookieCollection collection)

我看到这些文章很有帮助,但还有很多不足之处。

https://www.carlrippon.com/httpcontext-in-asp-net-core/ https://dotnetcoretutorials.com/2017/01/05/accessing-httpcontext-asp-net-core/

在 Controller 内部,它似乎是最简单的,但是大部分这些HttpContext.Current东西都散布在各个地方,域库等。

因此,在上面的两个 url 中,似乎使用下面的这一行,startup.cs 但是,我在主 asp.net 核心之外没有 startup.cs

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

然后在启动时我也看到了这篇文章 https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/

//one of many things added to project
services.AddHttpContextAccessor();

我意识到在过去的几年中已经提出了几个问题 - 希望一些勇敢的灵魂已经探索了这些东西,并对如何迁移这些东西有一些建议/答案。

移植方法:#1

  public Service(string key, LogRecord.CallType callType, string operation, string opArg, string opResponse)
    {
        this.Key = string.IsNullOrEmpty(key)
                       ? HttpContext.Current != null ? "Inbound/WebHttp: " + HttpContext.Current.Request.Url.AbsolutePath : string.Empty
                       : key;
        this.CallType = Enum.GetName(typeof(LogRecord.CallType), callType);
        this.URL = HttpContext.Current != null && callType == LogRecord.CallType.WebHttp
                       ? HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)
                       : string.Empty;
        this.Operation = operation;
        this.OpArg = opArg;
        this.OpResponse = opResponse;
    }

另一个:#2

   private static string CollectionToHtmlTable(HttpCookieCollection collection)
    {
        // Converts HttpCookieCollection to NameValueCollection
        var nvc = new NameValueCollection();
        foreach (string item in collection)
        {
            var httpCookie = collection[item];
            if (httpCookie != null)
            {
                nvc.Add(item, httpCookie.Value);
            }
        }

        return CollectionToHtmlTable(nvc);
    }

标签: c#asp.net-core

解决方案


问题是,您当前使用错误。

在 Controller 内部,它似乎是最简单的,但是大部分 HttpContext.Current 东西都散布在各个地方的域库等。

域库应该独立于前端。它是带有 Session 的网站还是有状态的 WPF 应用程序都没有关系。或者一个 RestFull Api。

也就是说,一个相对的快速修复是将HttpContext 注入到您的域类中

public DomainService(IHttpContextAccessor httpContext)
{
    _httpContext = httpContext;
}

然后,您可以通过依赖注入获取您的 DomainService。如果创作很复杂,您正在寻找一个Factory.

或者您可以在 ActionMethod 中自己创建服务(当然在这种情况下,您需要将服务的构造函数更改为 HttpContext:

public IActionResult Foo()
{
    var service = new DomainService(HttpContext)
}

也就是说:它被删除是有原因的。请不要在您的域中依赖 HttpContext!创建一个业务对象并将其作为参数提供给域。


不确定这是否是最好的方法,但我创建了一个 BusinessContext 类并将其注册为作用域。工厂负责使用所需数据创建它。


不要这样做:

如果您真的很疯狂,也许可以帮助您迁移。


推荐阅读