asp.net-mvcsessioniroutehandlercustom-routes

Protecting images in ASP.NET MVC (w/ custom RouteHandler)


I created a custom RouteHandler for images that I want protected. My RouteHandler simply takes a new route (graphics/{filename}) and does a lookup for the true file path, sets the mime type, and serves it up. That works fine. (http://www.mikesdotnetting.com/Article/126/ASP.NET-MVC-Prevent-Image-Leeching-with-a-Custom-RouteHandler)

What I wanted to do next was to do a check within my custom handler for a session variable that I would set earlier to make sure the person trying to view the image had permission to do so.

Basically, they would pass a login (enter a code), which would set a session variable that I would look for in the custom RouteHandler.

My problem is that I can't seem to get at the session data from within the custom RouteHandler.

Finally, my question is: How can I set data in a controller and have it available to me from within a custom RouteHandler on a subsequent request?


Solution

  • First, from the RequestContext passed in to the GetHttpHandler method, can you not access the Session via requestContext.HttpContext.Session? I am not sure, I could see this not working by default since it is so early in the pipeline.

    If not, you can always easily move the Session checking logic into the handler by adding the IRequiresSessionState interface to your handler.