在我的控制器中,我传递了一个要查看的模型
public IActionResult Forgotpassword()
{
System.Web.HttpContext.Current.Session["sessionString"] = "sample";
Forgotpasswordinfo Vmodel = new Forgotpasswordinfo();
return View(Vmodel);
}我使用System.Web.HttpContext.Current.Session["sessionString"] = "sample";创建会话变量,但它显示了一个错误,指出HttpContext不存在!?我遗漏了什么?
发布于 2021-01-04 05:54:18
下面的代码显示了如何设置内存中会话提供程序:
public class Startup
{
//...
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = ".TestApp.Session";
options.IdleTimeout = TimeSpan.FromSeconds(30);
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
}
}在调用UseSession之前无法访问HttpContext.Session。
在控制器中设置变量:
using Microsoft.AspNetCore.Http;
public IActionResult Index()
{
HttpContext.Session.SetString("Parameter", "bla bla");
return View();
}@using Microsoft.AspNetCore.Http;
@{
string parameter = Context.Session.GetString("Parameter");
}大多数情况下,上面的代码是Microsoft文档中示例的一部分。详细信息请参见Session and state management in ASP.NET Core。
https://stackoverflow.com/questions/65553993
复制相似问题