Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 维护同一浏览器会话的对象状态_C#_Asp.net_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 维护同一浏览器会话的对象状态

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

以下是我的ASP.NETWebAPI控制器代码。如您所见,这里使用了一个私有类对象BL,并实现了两个Get方法。对于第一个方法FetchAllDashboardByUserId(int userId),我传递用户id以便可以启动BL对象。在同一个浏览器会话中,如果调用了第二个get方法,那么我不想传递userid,因为默认情况下应该启动BL,但目前情况并非如此。对于第二个方法,BL为null,因此我必须将userid添加到方法GetCardDataUI的调用中(intuserid、intDashboardId、intCardId)。我的问题是如何避免它。我认为:

  • 我连续调用以下URL的单个打开浏览器是单个会话:

    webapi/ViewR?userId=1

    webapi/ViewR?userId=1&dashBoardID=1&carid=3

我不想在第二个URL中传递用户ID。请注意,如果我将类对象声明为静态,那么它将按预期工作,但这不是我想要的,它必须绑定到用户:

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...
但请记住以下几点:

  • 会话变量存储为
    object
    s,因此需要强制转换和/或类型检查
  • 会话变量可以是
    null
  • 会话在大约一段时间后可配置(在
    web.config
    中)过期
  • 默认会话状态在内存中,这意味着如果应用程序池重新启动,会话状态将消失-您可以将会话存储在文件或数据库中以保持更长时间
  • 除非使用持久性存储(文件、数据库),否则会话不会向外扩展
  • 存储在持久存储中的对象必须是可序列化的

您必须在会话状态中存储用户详细信息。看看这个@CodingDawg,感谢这确实是解决方案,它解决了isue for meIt确实是解决方案,但需要global.asax中的post authorization条目,如CodingDawg在上面的链接中所列,否则会话对象总是空的
... first request:

Session["userID"] = userID;

... next request:

int userID = (int)Session["userID"];  // should check for null first, but you get the idea...