简体   繁体   中英

Error handling ASP.NET MVC

I'm making error handling (403, 404, 500). I made ErrorController and Views :

public class ErrorController : Controller
{
    // GET: Error
    public ActionResult General(Exception exception)
    {
        return View("Exception", exception);
    }

    public ActionResult Http404()
    {
        return View();
    }

    public ActionResult Http403()
    {
        return View();
    }

} 

Then I wrote the following code in Global.asax.cs :

protected void Application_Error()
{
    var exception = Server.GetLastError();
    log.Error(exception);
    Response.Clear();
    var httpException = exception as HttpException;
    var routeData = new RouteData();
    routeData.Values.Add("controller", "Error");

    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();

        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values.Add("action", "Http403");
                break;
            case 404:
                routeData.Values.Add("action", "Http404");
                break;
            default:
                routeData.Values.Add("action", "Error");
                break;
        }
    }
    else
    {
        routeData.Values.Add("action", "General");
        routeData.Values.Add("exception", exception);
    }

    Server.ClearError();
    Response.TrySkipIisCustomErrors = true;
    IController errorsController = new ErrorController();
    errorsController.Execute(new RequestContext(
        new HttpContextWrapper(Context), routeData));
}

It works when url with controller name (example: http://localhost:62693/News/123 ), then I got error's 404 view.

But when I send url without controller name in it or with invalid controller name (example: http://localhost:62693/123 or http://localhost:62693/new/k ) I got only HTML code of error's 404 view.

How can I get error's 404 view with any urls?

Add this on webConfig file

<system.web>  
    <customErrors mode="On" defaultRedirect="~/Error/DefaultError">
</system.web>

// ErrorController ActionResult method...
public ActionResult DefaultError()
{
 return view();
}

handle error using RouteConfig

You use route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.

Note : The custom router must be added to the RouterConfig file.

This new {productId = @"\\d+" } is a RouteConstraints

  routes.MapRoute(
             "Product",
             "{controller}/{action}/{productId}",
             new {controller="Home", action="Product"},
             new {productId = @"\d+" }
            );

If the controlloller itself does not exist, IIS uses the preset 404 error page. Look at .net error pages in IIS features view.

TO SOLVE MY PROBLEM just add

Response.ContentType = "text/html";

Other method:

I find some other way to make custom errors.

web.config

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <error statusCode="404" responseMode="ExecuteURL" path="/Error/Http404" />
  </httpErrors>
</system.webServer>

Controller

public class ErrorController : Controller
{
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

This works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM