LalA LalA - 1 year ago 110
ASP.NET (C#) Question

Exception handling in Application_Error, what is sender.Context.Request?

I have Exception-handling code in my Application_Error. I got the code from stackoverflow, its working.

protected void Application_Error(Object sender, EventArgs e)

string currentController = "";
string currentAction = "";

HttpContext httpContext = ((MvcApplication)sender).Context;
HttpRequestWrapper httpRequest = new HttpRequestWrapper(httpContext.Request);

RouteData currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
if (!(currentRouteData == null))
if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
currentController = currentRouteData.Values["controller"].ToString();
if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
currentAction = currentRouteData.Values["action"].ToString();

var exception = Server.GetLastError();
if (exception == null)

// Clear the error

Models.Exception ex = new Models.Exception();
ex.ErrorMessage = exception.Message;
ex.ErrorUrl = String.Format("{0}/{1}", currentController, currentAction);



The problem is that I dont understand what is happening in these 2 linies:

HttpContext httpContext = ((MvcApplication)sender).Context;
HttpRequestWrapper httpRequest = new HttpRequestWrapper(httpContext.Request);

Can anyone explain what is happening here?

Answer Source

Nothing is happening there, the httpRequest variable isn't used afterwards.

It does give you a reference to the request during which the exception was generated, might you need it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download