Get/Set HttpContext Session Methods in BaseController vs Mocking HttpContextBase to create Get/Set methods

前端 未结 2 1926
遇见更好的自我
遇见更好的自我 2021-02-03 14:41

I created Get/Set HttpContext Session Methods in BaseController class and also Mocked HttpContextBase and created Get/Set methods.

Which is the best way to use it.

2条回答
  •  暖寄归人
    2021-02-03 15:05

    Just a little correction for the SetDataInSession method of the latest post. In my opinion, it´s a elegant solution! Thanks Darin Dimitrov.

    public static class SessionExtensions
    {
     public static T GetDataFromSession(this HttpSessionStateBase session, string key) {
                return (T)session[key];
            }
    
            public static void SetDataInSession(this HttpSessionStateBase session, string key, object value) {
                session[key] = value;
            }
    }
    
    • First create this class, and after remember to refer its namespace in the Controller class that will call this methods.

    • When getting the session value:

    string value = Session.GetDataFromSession("key1");

    The must be a compatible type with the object persisted in the session.

提交回复
热议问题