我有一个场景,我在使用Session将对象存储在一个控制器操作中并尝试检索另一个控制器操作。这两个操作都是从同一视图触发并驻留在同一个控制器上。不幸的是,我无法在第二个控制器中检索会话变量。会话ID保持不变,我确保在第一个操作中将对象写入会话。但是,在第一个操作中返回视图时,会话数据将消失。
这是我的控制器代码流 -
public PartialviewResult DoSearch(string paramCustId)
{
//invoking a method to perform a search task. I am also passing the controller session as a parameter
//this function is called in a separate thread and the main thread does not wait for it to complete before returning the view
multiSearch(paramCustId, Session);
}
return PartialView("_partialView1");
public void multiSearch(string searchParam, HttpSessionStateBase controllerSession)
{
//code to retrieve response from backend into the variable tempSearchSet
controllerSession["searchResult"] = tempSearchSet;
//verified that tempSearchSet is stored in Session under the key "searchResult" and Session.Count is 1.
}
//Another controller action that is triggered from the same view after a certain delay to fetch the data in session
public PartialViewResult PollSearchResults()
{
var tempSearchResult = Session["searchResult"] as List<SearchResultSet>;
//This is where i do not see data in the session. I have verified that the multiSearch method is complete and has updated the data in the session.
//here Session.SessionID is the same as above, but Session.Count is 0
}
有没有不同的方法来处理mvc中的Session或者我在这里缺少一些基本的东西?此外,是否有更好的方法来管理此缓存方案?
答案 0 :(得分:0)
找到解决方案。我不得不在Global.asax.cs的Session_Start方法中初始化会话变量。这一行使它对我有用。
HttpContext.Current.Session.Add("searchResult", new List<SearchResultSet>());
我仍然不清楚为什么需要这一行,因为会话变量get和set在没有初始化的第一个操作方法中工作。猜猜我会把它保留给未来的研究。