C# MVC HttpContext.Current.Items在单击链接后为空

C# MVC HttpContext.Current.Items在单击链接后为空,c#,asp.net-mvc-4,razor,C#,Asp.net Mvc 4,Razor,HttpContext.Items是否有限制?如果是的话,还有什么选择 在FirstController索引视图中,我正在设置一个项目 public class FirstController : Controller { public ActionResult Index() { HttpContext.Items["Sample"] = "DATA"; return View(); } } <a href="/SecondCon

HttpContext.Items是否有限制?如果是的话,还有什么选择

FirstController索引视图中,我正在设置一个项目

public class FirstController : Controller
{
    public ActionResult Index()
    {
        HttpContext.Items["Sample"] = "DATA";
        return View();
    }
}

<a href="/SecondController/TestView">Sample Link</a>

HttpContext
Items
属性用于在单个请求中共享数据。当您在第一个控制器中将该值设置为
Sample
键时,请求管道一完成,它就会被丢弃

我想您正在寻找可通过属性访问的
HttpSessionState
。您可以将代码中的
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请求保留在内存中,然后将其释放

“获取可用于在HTTP请求期间组织和共享数据[…]的键/值集合。”

您需要一种有状态机制(如会话)来在请求之间保留数据:

Session["Sample"] = "DATA";

另请参见。

我不想使用会话。使用自定义属性可以做到这一点吗?自定义属性不会解决您的问题。解释您不想使用会话的原因,并请单击“”链接查看备选方案。
Session["Sample"] = "DATA";