I donβt remember where I saw this code or what I changed, but it works fine in my MVC web application.
Web.config
<system.web> <compilation debug="true" targetFramework="4.5.1" /> <httpRuntime targetFramework="4.5.1" /> <customErrors mode="Off" /> </system.web>
Global.aspx
protected void Application_EndRequest(Object sender, EventArgs e) { ErrorConfig.Handle(Context); }
ErrorConfig.cs
namespace Web.UI.Models.Errors { public static class ErrorConfig { public static void Handle(HttpContext context) { switch (context.Response.StatusCode) { case 401: Show(context, 401); break; case 404: Show(context, 404); break; case 500: Show(context, 500); break; } }
ErrorController
public class ErrorController : Controller { // GET: Error [HttpGet] public ViewResult Index(Int32? id) { var statusCode = id.HasValue ? id.Value : 500; var error = new HandleErrorInfo(new Exception("An exception with error " + statusCode + " occurred!"), "Error", "Index"); int errorCode = statusCode; ViewBag.error = errorCode; return View("Error"); } }
ErrorsViewModel
namespace Web.UI.Models.Errors { public class ErrorViewModel { public string DisplayErrorMessage { get; set; } public string DisplayErrorPageTitle { get; set; } } }
Then on the page with the message about the shared folder, add
@model Web.UI.Models.Errors.ErrorViewModel @{ int errorCode = Convert.ToInt32(@ViewBag.error); switch (errorCode) { case 404: ViewBag.Title = "404 Page Not Found"; Html.RenderPartial("~/Views/Shared/ErrorPages/HttpError404.cshtml"); break; case 500: ViewBag.Title = "Error Occurred"; Html.RenderPartial("~/Views/Shared/_Error.cshtml"); break; default: ViewBag.Title = @Model.DisplayErrorPageTitle; Html.RenderPartial("~/Views/Shared/ErrorPages/HttpNoResultsFound.cshtml"); break; } }
The above returns status 404 for the page not found and 500 for the error, I hope that it helps
source share