Brian David Berman
Brian David Berman

Reputation: 7684

Access session data from custom RouteHandler?

I am building onto the example found here:

http://www.mikesdotnetting.com/Article/126/ASP.NET-MVC-Prevent-Image-Leeching-with-a-Custom-RouteHandler

What I would like to do now is have some logic that checks for certain data in session before allowing the valid image to show. Is it possible to access session data from within the custom RouteHandler or any other type of persisted data?

Upvotes: 0

Views: 980

Answers (2)

Jan Kukacka
Jan Kukacka

Reputation: 1265

I have published solution for this problem as answer to another question.

Look at the application life cycle overview (https://msdn.microsoft.com/en-us/library/bb470252(v=vs.140).aspx), particulary the row The request is processed by the HttpApplication pipeline. in the table Life Cycle Stages.

Whereas the function GetHttpHandler of your IRouteHandler object is invoked in the phase 10 (Raise the MapRequestHandler event.) of the pipeline, Session is restored in the phase 12 (Raise the AcquireRequestState event.). That is why you cannot access Session variables during the GetHttpHandler function and RequestContext.HttpContext.Session is always null.

Upvotes: 2

John Farrell
John Farrell

Reputation: 24754

You have access the session right from the requestContext:

private static void ProcessRequest(RequestContext requestContext)
{
   var session = requestContext.HttpContext.Session;

Upvotes: 1

Related Questions