Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller SessionStateBehavior is ReadOnly and I can update Session Variable

I expect that if controller has attribute SessionStateBehavior.ReadOnly then I can't change session variables inside this controller but I can change values.

I try this code

 [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
    public class GLobalController : Controller
    {
      public  ActionResult Index()
        {
            Session["xxx"] = DateTime.Now.ToString();
            return View();
        }
like image 511
user1223234 Avatar asked Sep 04 '12 12:09

user1223234


2 Answers

see Writing to a read only session in MVC 3+

That post claims the behavior is inconsistent. I am definitely able to write to Session in Controllers using ReadOnly.

I Would treat it like this:

  • Required means you are requesting a exclusive lock on Session (i.e. no parallel processing of requests for the same sessionID)
  • ReadOnly means you are requesting a non-exclusive lock on Session (i.e. your request still has to wait for requests with an exclusive lock to finish, but you can process requests with non-exclusive locks in parallel. However it is up to you to ensure that your code doesn't write to Session. It's not necessarily enforced by the framework)

    I realize this is counter to http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatebehavior.aspx

    Read-only session state is enabled for the request. This means that session state cannot be updated.

    but it seems you in fact can update session state under some scenarios.

  • like image 86
    turnhose Avatar answered Nov 07 '22 03:11

    turnhose


    According to Patrick Y. Ng (Software Engineer at Microsoft) who designed and developed the Session State engine of ASP.NET:

    Even though EnableSessionState is marked as ReadOnly, in InProc state the user can still modify the session. The only difference is that the session will not be locked during the request. This limitation is by-design. And I'm sorry that it’s not documented in MSDN.

    There is much more useful information about session state in this post. It is really worth reading.

    like image 15
    piter entity Avatar answered Nov 07 '22 03:11

    piter entity