【发布时间】:2018-08-07 00:10:55
【问题描述】:
我没有看到太多关于将 asp.net mvc 4.6 应用程序移植到 1.0 到 2.0 和 2.0 的 asp.net core 2.1 的信息。到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 的东西散布在各个地方的域库等。
所以在上面的两个网址中,似乎在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);
}
【问题讨论】:
-
不太清楚你在问什么。你想在其他项目的类中注入
HttpContextAccessor吗?请注意,HttpContext.Current已被弃用,因为它被广泛滥用,所以你应该问自己是否真的需要它 -
“但是,我在主 asp.net 核心之外没有 startup.cs” - 这不是您要找的吗?您在使用
IHttpContextAccessor和(可能)IActionContextAcccessor时遇到了什么问题? -
@CamiloTerevinto 如果我想移植一个应用程序——我粘贴的这些 url 中的这些黑客,尤其是 Strathweb 的,没有请求。路径——需要基于以前开发人员编写的所有代码用于服务、安全、错误日志身份等。
-
@john - 在 asp.net 中只有一个 startup.cs 文件 - 但是我希望在无法使用上述方法的类库中。希望基本上得到移植
-
你目前是否使用依赖注入?
标签: c# asp.net-core