点击链接后,MVC HttpContext.Current.Items为空
本文关键字:HttpContext Current Items 为空 MVC 链接 | 更新日期: 2023-09-27 17:52:41
是否有HttpContext的限制?项目 ?如果是这样,还有什么替代方案?
在FirstController索引视图中,我正在设置一个项目。
public class FirstController : Controller
{
public ActionResult Index()
{
HttpContext.Items["Sample"] = "DATA";
return View();
}
}
<a href="/SecondController/TestView">Sample Link</a>
当我试图获得值在SecondController它给我null而不是'DATA'
public class SecondController : Controller
{
public ActionResult TestView()
{
string text = HttpContext.Current.Items["Sample"];
return View();
}
}
HttpContext.Items
"获取可用于组织和共享数据的键/值集合[…]在HTTP请求"期间。
你需要一个像Session这样的有状态机制来保存请求之间的数据:
Session["Sample"] = "DATA";
参见在asp.mvc中请求之间存储数据的正确方法.
HttpContext
的Items
属性用于在单个请求中共享数据。当您在第一个控制器中将值设置为Sample
键时,一旦请求管道完成,它就会被丢弃。
我认为您正在寻找HttpSessionState
,可通过HttpContext.Session
属性访问。您可以将代码中的HttpContext.Items
替换为HttpContext.Session
,它应该可以正常工作。
public class FirstController : Controller
{
public ActionResult Index()
{
HttpContext.Session["Sample"] = "DATA";
return View();
}
}
public class SecondController : Controller
{
public ActionResult TestView()
{
string text = HttpContext.Current.Session["Sample"];
return View();
}
}
HttpContext
的数据为单个HTTP请求保留在内存中,然后它们被处理。