I had a little bit of code that I was duplicating for ASP.NET and SignalR and I decided to rewrite it as OWIN middleware to remove this duplication.
Once I was running it I noticed that HttpContext.Current.Session
was null, and I didn't see any session object on the IOwinContext
that my middleware has.
Is it possible to access the http session from OWIN?
Yes, but it's quite a hack. It also won't work with SignalR because SignalR MUST run before session is acquired to prevent long session locks.
Do this to enable session for any request:
Then you can access the session with either
HttpContext.Current.Session
orThis answer is a remix from the initial answer, so the gist of it should be attributed to @Tratcher. It's different enough though to post it seperately instead of suggesting an edit.
Supposing you want to make a small OWIN app for basic testing purposes (e.g. as a stub/fake for a bigger API when doing integration tests), including a slightly hakish way of using session state would work just fine.
First up, you need these:
With those you can create a helper method:
You could also create that as an extension method as the original answer did.
Note that if you don't use the
UseStageMarker
you would encounter this error:In any case, with the above you can now use HttpContext in your OWIN app like this:
If you fire up IIS Express with this little app you'll first get:
Then if you go to
http://localhost:12345/write
you'll get:Then if you go back / go to any other url on that host you'll get:
Or something similar.