您好
在动作中,我设置了HttpContext.Current.Items.Add(...)
。现在我重定向到同一个控制器中的另一个动作。我无法获得当前的HttpContext。
这是不可能的。有没有解决此问题的方法,而不是使用临时数据。
答案 0 :(得分:3)
HttpContext仅在当前HTTP请求期间可用。如果您重新映射到另一个操作,该操作是浏览器使用另一个HttpContext发送的另一个HTTP请求。如果您想在请求之间保留数据,可以使用TempData(仅适用于1次重定向)或Session。在封面下,TempData使用会话作为存储,但在重定向后它会被框架自动驱逐。
TempData示例:
public ActionResult A()
{
TempData["foo"] = "bar";
return RedirectToAction("B");
}
public ActionResult B()
{
// TempData["foo"] will be available here
// if this action is called after redirecting
// from A
var bar = TempData["foo"] as string;
// TempData["foo"] will no longer be available in C
return RedirectToAction("C");
}
会话示例:
public ActionResult A()
{
Session["foo"] = "bar";
return RedirectToAction("B");
}
public ActionResult B()
{
var bar = Session["foo"] as string;
// Session["foo"] will still be available in C
return RedirectToAction("C");
}