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

前端 未结 2 1920
遇见更好的自我
遇见更好的自我 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:07

    The second one seems the best. Although I would probably write those two as extension methods to the HttpSessionStateBase instead of putting them into a base controller. Like this:

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

    and then inside the controllers, or helpers, or something that has an instance of HttpSessionStateBase use it:

    public ActionResult Index()
    {
        Session.SetDataInSession("key1", "value1");
        string value = Session.GetDataFromSession("key1");
        ...
    }
    

    Writing session wrappers is useless in ASP.NET MVC as the HttpSessionStateBase provided by the framework is already an abstract class which could be easily mocked in unit tests.

提交回复
热议问题