ASP.NET MVC Custom Error Handling Application_Error Global.Asax

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:

protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();

HttpException httpException = exception as HttpException;

if (httpException != null) {
string action;

switch (httpException.GetHttpCode()) {
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}

// clear error on server
Server.ClearError();

Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}

Then your controller will receive whatever you want:

// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
return View("SomeView", message);
}

There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.

Application_Error custom error handler in Global.asax

Well,

I found temporary solution for my problem. It's not the best but you may need it.

In Web.Config

<system.web>
<customErrors mode="On" /> // On or Off doesn't matter ISS 7 or newer version
</system.web>
<system.webServer>
<httpErrors existingResponse="Auto">
<clear/>
<error statusCode="404" path="/notfound.aspx" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>

In Global.asax

HttpException httpexception = Server.GetLastError().GetBaseException() as HttpException;
string ex_message = httpexception.InnerException;
// send or save errors here
Server.ClearError();
Response.Redirect("error");

Note: I didn't handle 404 error from codebehind, web.configuration helps about it.

Implementing a custom error in global.asax

EDIT:

The answer is not obvious, but this seems to explain it: http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs

If you scroll down a ways, you'll find this lovely tidbit:

Note: The custom error page is only displayed when a request is made
to a resource handled by the ASP.NET engine.
As we discussed in the
Core Differences Between IIS and the ASP.NET Development Server
tutorial , the web server may handle certain requests itself. By
default, the IIS web server processes requests for static content like
images and HTML files without invoking the ASP.NET engine.
Consequently, if the user requests a non-existent image file they will
get back IIS's default 404 error message rather than ASP.NET's
configured error page.

I've emphasized the first line. I tested this out in the default template, and sure enough, this URL:

http://localhost:49320/fkljflkfjelk

gets you the default IIS page, whereas simply appending a .aspx makes the Application_Error kick in. So, it sounds like you need to enable customErrors/httpErrors if you want to have all errors handled.

For IIS <= 6, add to <system.web>:

<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/404.aspx"/>
<error statusCode="500" redirect="/500.aspx"/>
</customErrors>

For IIS7+, add to <system.webServer>:

<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="/404.aspx" responseMode="ExecuteURL"/>
<remove statusCode="500"/>
<error statusCode="500" path="/500.aspx" responseMode="ExecuteURL"/>
</httpErrors>

I'll leave the original answer in case someone finds it useful.


I believe you need to clear the existing error code from the response, otherwise IIS ignores your redirect in favor of handling the error. There's also a Boolean flag, TrySkipIisCustomErrors, you can set for newer versions of IIS (7+).

So, something like this:

void Application_Error(object sender, EventArgs e)
{
Exception TheError = Server.GetLastError();
Server.ClearError();

// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;

if (TheError is HttpException && ((HttpException)TheError).GetHttpCode() == 404)
{
Response.Redirect("~/404.aspx");
}
else
{
Response.Redirect("~/500.aspx");
}
}

Is global.asax Application_Error event not fired if custom errors are turned on?

If you do not call Server.ClearError or trap the error in the Page_Error or Application_Error event handler, the error is handled based on the settings in the section of the Web.config file.

See this SO question for more information

Redirect to Error Page Fail on Application Error in Global.asax (MVC)

Try the following:

protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc =((MvcHandler)ctx.CurrentHandler).RequestContext;
rc.RouteData.Values["action"] = "AllErrors";

rc.RouteData.Values["controller"] = "HndlError";
rc.RouteData.Values["id"] = ErrorMessage ;

IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, "HndlError");
controller.Execute(rc);
ctx.Server.ClearError();
}

Custom Error using Global.asax asp.net

    protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError();

if(ex is HttpException)
{
HttpException httpEx = (HttpException)ex;

if(httpEx.GetHttpCode() == 401)
{
Response.Redirect("YourPage.aspx");
}
}
}

Yes it is possible. Here is little code example. This should be added in Global.asax.cs.



Related Topics



Leave a reply



Submit