HttpContext.Current.Session is null requesting ima

2019-07-30 13:56发布

问题:

I'm building a ASP MVC application.

When I request a route to a controller, for example:

http://myserver/sales/id/5

the session object HttpContext.Current.Session is working perfectly.

However, when I'm requesting an image or a script, for example:

http://myserver/Scripts/jquery-1.4.1.js

the session object HttpContext.Current.Session is null

How I can distinguish this situation from other when there is no "real" session (for example first login)?

回答1:

Why would you need a session for retrieving a static file?

Unless you are using a dynamic handler, there is absolutely no need for session to retrieve such content.

My point is that session does not serve any useful purpose for retrieving static content, so it is not available.



回答2:

@Oded is right, this is an optimization in asp.net. If you need the session to be available, then you will need the request to go to a handler that has indicated it needs the session. If you are writing your own handler, then it simply needs to implement the marker interface IRequiresSessionState.

This optimization isn't just for the current request, but any parallel requests that you are making as multiple requests that use the same session are handled in a serial fashion. Read my blog post for more info on this.