我们目前正在使用ASP.NET Core重写/转换我们的ASP.NET WebForms应用程序.尽量避免重新设计.
我们HttpContext在类库中使用了一个部分来检查当前状态.如何HttpContext.Current在.NET Core 1.0中访问?
var current = HttpContext.Current;
if (current == null)
{
// do something here
// string connection = Configuration.GetConnectionString("MyDb");
}
Run Code Online (Sandbox Code Playgroud)
我需要访问它才能构建当前的应用程序主机.
$"{current.Request.Url.Scheme}://{current.Request.Url.Host}{(current.Request.Url.Port == 80 ? "" : ":" + current.Request.Url.Port)}";
Run Code Online (Sandbox Code Playgroud) 我需要HttpContext在静态方法或实用程序服务中访问当前.
使用经典的ASP.NET MVC System.Web,我只是用来HttpContext.Current静态访问上下文.但是我如何在ASP.NET Core中执行此操作?
我试图从视图内部访问会话数据.
使用案例:我将状态消息存储在将显示在页面顶部的会话中.目前我通过使用一个DisplayMessages()函数来实现它,该函数设置一些ViewData[....]属性并在每个控制器动作的开头调用它.
目标:我只想设置状态消息一次,而不需要控制器中的其他代码来显示下一页加载的消息.
所以我试图直接从视图中访问存储在会话中的消息.
到目前为止,我尝试了以下内容:
next()到next.invoke()的意见建议
HttpContext并且Session.IsAvailable是真的,但会话中没有数据.我正在尝试在ASP.NET Core 2.1项目中的帮助器类中访问HttpContext.Session对象。
当我尝试访问HttpContext.Session时,出现以下错误。
CS0120非静态字段,方法或属性'HttpContext.Session'需要对象引用
使用.NET 4.x ASP.NET,可以使用“ HttpContext.Current.Session”轻松访问它。
这是我的课:
public class MySession
{
public void Foo()
{
HttpContext.Session.SetString("Name", "The Doctor"); // will not work
HttpContext.Session.SetInt32("Age", 773); // will not work
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set …Run Code Online (Sandbox Code Playgroud)