C# 维护同一浏览器会话的对象状态
以下是我的ASP.NETWebAPI控制器代码。如您所见,这里使用了一个私有类对象BL,并实现了两个Get方法。对于第一个方法FetchAllDashboardByUserId(int userId),我传递用户id以便可以启动BL对象。在同一个浏览器会话中,如果调用了第二个get方法,那么我不想传递userid,因为默认情况下应该启动BL,但目前情况并非如此。对于第二个方法,BL为null,因此我必须将userid添加到方法GetCardDataUI的调用中(intuserid、intDashboardId、intCardId)。我的问题是如何避免它。我认为:C# 维护同一浏览器会话的对象状态,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,以下是我的ASP.NETWebAPI控制器代码。如您所见,这里使用了一个私有类对象BL,并实现了两个Get方法。对于第一个方法FetchAllDashboardByUserId(int userId),我传递用户id以便可以启动BL对象。在同一个浏览器会话中,如果调用了第二个get方法,那么我不想传递userid,因为默认情况下应该启动BL,但目前情况并非如此。对于第二个方法,BL为null,因此我必须将userid添加到方法GetCardDataUI的调用中(intuserid、intDash
- 我连续调用以下URL的单个打开浏览器是单个会话: webapi/ViewR?userId=1 webapi/ViewR?userId=1&dashBoardID=1&carid=3
public class ViewRController : ApiController
{
// BL object for a user
private static BL accessBL = null;
// HTTP GET for Webapi/ViewR (Webapi - name of API, ViewR - Controller with implementation)
[AcceptVerbs("Get")]
public List<DashboardUI> FetchAllDashboardByUserId(int userId)
{
if (accessBL == null)
accessBL = new BL(userId);
// Use BL object for entity processing
}
[AcceptVerbs("Get")]
public CardDataGetUI GetCardDataUI(int userId, int dashBoardID, int cardID)
{
if (accessBL == null)
accessBL = new BL(userId);
// Use BL object for entity processing
}
}
您可以轻松地将数据存储在
会话中
:
... first request:
Session["userID"] = userID;
... next request:
int userID = (int)Session["userID"]; // should check for null first, but you get the idea...
但请记住以下几点:
- 会话变量存储为
s,因此需要强制转换和/或类型检查object
- 会话变量可以是
null
- 会话在大约一段时间后可配置(在
中)过期web.config
- 默认会话状态在内存中,这意味着如果应用程序池重新启动,会话状态将消失-您可以将会话存储在文件或数据库中以保持更长时间
- 除非使用持久性存储(文件、数据库),否则会话不会向外扩展
- 存储在持久存储中的对象必须是可序列化的
... first request:
Session["userID"] = userID;
... next request:
int userID = (int)Session["userID"]; // should check for null first, but you get the idea...