我们目前正在使用ASP.NET核心重写/转换我们的ASP.NET WebForms应用程序。尽量避免重新设计。
有一节我们在类库中使用HttpContext
来检查当前状态。如何在.NET Core1.0中访问HttpContext.Current
?
var current = HttpContext.Current;
if (current == null)
{
// do something here
// string connection = Configuration.GetConnectionString("MyDb");
}
为了构造当前的应用程序主机,我需要访问它。
$"{current.Request.Url.Scheme}://{current.Request.Url.Host}{(current.Request.Url.Port == 80 ? "" : ":" + current.Request.Url.Port)}";
发布于 2016-09-19 18:28:52
如果您确实需要对当前上下文进行静态访问,那么有一个解决方案。在Startup.Configure中(…。)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
当你需要它的时候,你可以用以下命令获得它:
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
我希望这能有所帮助。请记住,这种变通方法是在您别无选择时使用的。最佳实践是使用去依赖注入。
https://stackoverflow.com/questions/38571032
复制相似问题