我们目前正在使用ASP.NET Core重写/转换我们的ASP.NET WebForms应用程序。尽量避免重新设计。
我们在类库中使用HttpContext
来检查当前状态。如何在.NET Core 1.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)}";
答案 0 :(得分:189)
作为一般规则,将Web窗体或MVC5应用程序转换为ASP.NET Core 将需要进行大量重构。
在ASP.NET Core中删除了 HttpContext.Current
。从单独的类库访问当前HTTP上下文是ASP.NET Core试图避免的混乱体系结构的类型。有几种方法可以在ASP.NET Core中重新构建它。
您可以通过任何控制器上的HttpContext
属性访问当前的HTTP上下文。与原始代码示例最接近的是将HttpContext
传递给您正在调用的方法:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
如果您正在为ASP.NET Core管道编写custom middleware,则当前请求的HttpContext
会自动传递到您的Invoke
方法中:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
最后,您可以使用IHttpContextAccessor
帮助程序服务来获取由ASP.NET Core依赖注入系统管理的任何类中的HTTP上下文。当您拥有控制器使用的公共服务时,这非常有用。
在构造函数中请求此接口:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
然后,您可以安全地访问当前的HTTP上下文:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
默认情况下始终不会添加到服务容器中,因此请在ConfigureServices
中注册以确保安全:
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
答案 1 :(得分:38)
Necromancing。
是的你可以,这是怎么回事。
那些迁移大型 junks 代码块的秘密提示:
下面的方法是一个黑客的邪恶痈,积极参与执行撒旦的快速工作(在.NET核心框架开发人员的眼中),但它的工作:
在public class Startup
添加属性
public IConfigurationRoot Configuration { get; }
然后在ConfigureServices中将单个IHttpContextAccessor添加到DI中。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
然后在Configure
中 public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
添加DI参数IServiceProvider svp
,方法如下:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
接下来,为System.Web创建一个替换类:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
现在在Configure中,您添加了IServiceProvider svp
,将此服务提供程序保存到静态变量&#34; ServiceProvider&#34;在刚创建的虚拟类System.Web.HttpContext(System.Web.HttpContext.ServiceProvider)
并将HostingEnvironment.IsHosted设置为true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
这基本上是System.Web所做的,只是你从未见过它(我猜这个变量被声明为内部而不是公共)。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
就像在ASP.NET Web表单中一样,当你没有尝试访问HttpContext时,你会得到一个NullReference,例如它曾经在全局Application_Start
中的.asax。
我再次强调,这只有在您实际添加
时才有效services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
像我写的那样你应该。 也许更易于维护的方法是添加此辅助类
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
然后在Startup-&gt; Configure
中调用HttpContext.Configurepublic void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
答案 2 :(得分:8)
如果您确实需要对当前上下文的静态访问,则可以使用此解决方案。 在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;
我希望有所帮助。请记住,当您无法选择时,此解决方法。最佳做法是使用de dependency injection。