我没有看到太多有关将 asp.net mvc 4.6 应用程序移植到 asp.net core 2.1 吨 1.0 到 2.0 和 2.0 的信息。到 2.1 文章,但变化有点陡峭。
好吧,我已经浏览过 google 和 stackoverflow,我正在尝试/想要做的就是转换旧的 .net 应用程序并将其引入 .net core。
我认为问题的一些罪魁祸首如下:
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/
在控制器内部,它似乎是最简单的,但大部分HttpContext.Current内容都散布在域库等各个地方。
因此,在上面的两个网址中,似乎使用下面的这一行startup.cs
,但是,我在主 asp.net core 之外没有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);
    }
问题是,你目前的使用方式是错误的。
在 Controller 内部,它似乎是最简单的,但是大多数 HttpContext.Current 的东西都散布在域库等的各个地方。
域库应该独立于前端。它是带有 Session 的网站还是有状态的 WPF 应用程序并不重要。或者 RestFull Api。
也就是说,一个相对的快速修复是将HttpContext注入到您的域类中。
public DomainService(IHttpContextAccessor httpContext)
{
    _httpContext = httpContext;
}
然后,您可以通过依赖注入获取您的 DomainService。如果创作很复杂,您正在寻找一个Factory.
或者您可以在 ActionMethod 中自己创建 Service(当然在这种情况下您需要将 Service 的构造函数更改为 HttpContext:
public IActionResult Foo()
{
    var service = new DomainService(HttpContext)
}
也就是说:它被删除是有原因的。请不要依赖您域中的 HttpContext!创建一个业务对象并将其作为参数提供给域。
不确定这是否是最好的方法,但我创建了一个 BusinessContext 类并将其注册为作用域。工厂负责用所需的数据创建它。
如果你真的很疯狂,也许这可以帮助你移民。
| 归档时间: | 
 | 
| 查看次数: | 9067 次 | 
| 最近记录: |