0

Very weird behavior.

In my controller I have added an attribute [SessionState(SessionStateBehavior.ReadOnly)] to be able to handle parallel requests.

When added the attribute I see that between requests I lose my session variables. I have seen that the session variables are getting updated, but are lost somewhere along the way.

I have added some debug logs in a couple of life cycle events:

Reqeust1:
Application_PreRequestHandlerExecute: Session.Count:0
Application_PostRequestHandlerExecute: Session.Count:3

Reqeust2
Application_PreRequestHandlerExecute: Session.Count:0
Application_PostRequestHandlerExecute: Session.Count:0

Using .NetFrameWork 4.5.2, Microsoft.AspNet.Mvc.5.2.3

omriman12
  • 1,644
  • 7
  • 25
  • 48
  • `ReadOnly` means you shouldn't write to it. If you want to write to it, don't use `ReadOnly`. – mjwills Oct 02 '19 at 13:36
  • @mjwills that's not true, ReadOnly only talks about the lock used, read online. Also as I wrote - the variables are getting updated in the thread context.. – omriman12 Oct 02 '19 at 13:39
  • https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionstatebehavior?view=netframework-4.8 `Read-only session state is enabled for the request. This means that session state cannot be updated. This setting overrides whatever session state behavior would have been determined by inspecting the handler for the request.` Now, for some framework versions it may _work_ as per https://stackoverflow.com/questions/12263086/controller-sessionstatebehavior-is-readonly-and-i-can-update-session-variable . But it isn't _documented_ to work. `This means that` is quite clear. – mjwills Oct 02 '19 at 13:40
  • Now, if you ignore the docs and hope for it to work - the issue is likely that the lack of locking means that the two concurrent requests have R2 trashing the session state of R1. – mjwills Oct 02 '19 at 13:42
  • @mjwills the docs says that, but i have seen many posts like this one: `https://stackoverflow.com/questions/12263086/controller-sessionstatebehavior-is-readonly-and-i-can-update-session-variable` – omriman12 Oct 02 '19 at 13:43
  • @mjwills you edited it after i posted :) the thing is I tested it on a project with 4.5.2 and it worked. now i tested on another project also with 4.5.2 and it doesn't work for some reason, so I am a bit confused about it. I understand what you are saying that I should follow the docs. – omriman12 Oct 02 '19 at 13:48
  • `it doesn't work for some reason` The docs said not to do something. You did it in one place and it worked. In another place it didn't work. That is the nature of race conditions. The long term solution is to treat read-only as read-only. :) – mjwills Oct 02 '19 at 13:50

0 Answers0