GomuGomuNoRocket
GomuGomuNoRocket

Reputation: 819

Custom Error pages in MVC ASP NET for all errors

i want in my app to have custom error pages for 401, 404 etc error codes.

I try this but doesn't work? In Web.config

<customErrors mode="Off" /> //Under system.web

<httpErrors errorMode="Custom" existingResponse="Replace" >//Under system.webServer
  <clear />
  <remove statusCode="401"/>
  <error statusCode="401" responseMode="ExecuteURL" path="/Error/Unauthorized" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>

I have create also Error controller and Unauthorized views.

How can this work?

Upvotes: 2

Views: 1906

Answers (1)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Example:

web.config:

in system.web add

<customErrors mode="RemoteOnly"  defaultRedirect="~/error">//RemoteOnly means that on local network you will see real errors
  <error statusCode="401" path="~/Error/Unauthorized" />
  <error statusCode="404" path="~/Error/NotFound" />
  <error statusCode="500" path="~/Error" />
</customErrors>

in system.webServer add

<httpErrors errorMode="Detailed" /> 

Controller: your controller something like

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }
}

View: and your view something like

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>          
        </div>
    }
</div>

Hopefully it's help for you.

Upvotes: 2

Related Questions