Tuesday, July 19, 2011

How to get an HttpContextBase object from HttpContext.Current?

I need to investigate what's going on inside the ASP.NET MVC RouteTable. That can be done by calling:

RouteTable.Routes.GetRouteData(httpContextBase);

The problem is that httpContextBase object. You can't simply use HttpContext.Current, because that does not inherit from HttpContextBase like the name suggests. HttpContextBase was introduced to abstract away direct access to HttpContext (great for testing obviously), but since it's not a sub class, how do you get from HttpContext to HttpContextBase?

It's easy, simply instantiate an HttpContextWrapper object. This wraps access to members of HttpContext.

var wrapper = new HttpContextWrapper(HttpContext.Current);

Pass this object to RouteTable.Routes.GetRouteData. Easy. 

Posted via email from The Coder's Perspective

1 comments:

Anonymous said...

Saved me a lot of messing around trying to create an instance of the HttpContext.Current for my MVC controlers.

Sweet as a nut!
Ta,
Michael.McD

Share/Save/Bookmark