维护相同浏览器会话的对象状态

时间:2014-06-24 18:14:32

标签: c# asp.net asp.net-mvc asp.net-mvc-4

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

  • 我对以下网址进行连续调用的单一开放式浏览器是单个会话:

    的WebAPI / ViewR?用户id = 1

    的WebAPI / ViewR用户id = 1&安培; dashBoardID = 1&安培; CardId中= 3

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

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
        }
    }

我希望第二种方法实现如何:

[AcceptVerbs("Get")]
            public CardDataGetUI GetCardDataUI(int dashBoardID, int cardID)
            {
               // Use BL class object created in last call for entity processing
               // Should not pass userid again
            }

1 个答案:

答案 0 :(得分:2)

您可以轻松地将数据存储在Session

... 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)约时间后到期
  • 默认会话状态是内存中,这意味着如果重新启动应用程序池会话状态消失 - 您可以将会话存储在文件或数据库中以保持更长时间
  • 除非您使用持久存储(文件,数据库),否则会话不会向外扩展
  • 存储在持久存储中的对象必须是可序列化的
相关问题