How to show custom 404 page in ASP.NET-MVC?
Whenever any 404 url ββis on my site, I want to show a custom 404 page that is rendered using ASP.NET-MVC. However, I do not want to use the wildcard routes approach, because it will disable standard web forms. Currently my code looks like this:
if (serverException is HttpException && ((HttpException)serverException).GetHttpCode() == 404)
{
//Server.Transfer("~/Test.aspx"); //1
//Server.Transfer("~/error/gf54tvmdfguj85fghf/404"); //2
}
this code is inside App_Error
// 1 works. Test.aspx is a standard web form
// 2 doesn't work as this is the asp.net-mvc route
How do I make the MVC route work?
+2
source to share
1 answer
You can use application error event ... for example:
protected void Application_Error(object sender, EventArgs e)
{
//Check if it a 404 error:
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
if(httpException.GetHttpCode() == 404) {
//Redirect to the error route
Response.Redirect(String.Format("~/Error/404/?message={0}", exception.Message));
}
}
-1
source to share