Christian Nielsen
Christian Nielsen

Reputation: 599

Accessing RequestContext from global.asax

Does anyone know how to get the current RequestContext from the Application_Error event in global.asax?? My problem is that i need to do a redirect, and thereby need to have the url generated using UrlHelper - which takes the aformentioned RequestContext.

Upvotes: 11

Views: 7362

Answers (3)

Medeni Baykal
Medeni Baykal

Reputation: 4333

You can access the request context using

HttpContext.Current.Request.RequestContext

Or, if you're in the Global.asax you can use

Context.Request.RequestContext

directly.

Upvotes: 7

Oved D
Oved D

Reputation: 7442

Create an HttpContextBase from the Current HttpContext, and from that you can generate a UrlHelper:

// Create Http Context Base from current Context
var contextBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);
// Get its request context
System.Web.Routing.RequestContext requestContext = contextBase.Request.RequestContext;
// Build url helper from request context
var urlHelper = new System.Web.Mvc.UrlHelper(requestContext);

Upvotes: 0

Gene Hallman
Gene Hallman

Reputation: 381

While there is no direct way of accessing the RequestContext, you can create one yourself:

RequestContext context = new RequestContext(new HttpContextWrapper(HttpContext.Current), RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)))

So the UrlHelper can be constructed via:

UrlHelper helper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current))));

Not pretty, but it gets the job done.

Upvotes: 11

Related Questions