Alan Shortis
Alan Shortis

Reputation: 1109

MVC error page controller and custom routing

I have modified my routing to include the culture in the URL

routes.MapRoute(
            name: "Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { culture = "en-GB", controller = "StyleGuide", action = "Template", id = UrlParameter.Optional },
            constraints: new { culture = @"[a-z]{2}-[A-Z]{2}" }
        );

I have also created ErrorController and defined my error pages in Web.config:

<customErrors mode="On" defaultRedirect="~/Error/Index">
  <error statusCode="404" redirect="~/Error/NotFound"/>
</customErrors>

I am also using mvcSiteMapProvider, so I have included my new error pages and am able to access them via the menu as it uses a URL that includes my culture: localhost/en-GB/Error/NotFound

When an exception is thrown the error pages aren't being found because the culture is missing from the redirects defined in Web.Config.

How can I include the culture when redirecting to my error pages?

Upvotes: 1

Views: 4709

Answers (1)

martinoss
martinoss

Reputation: 5458

This is a good article describing the possibilities and limitations about error handling approaches in ASP.NET MVC: Exception Handling in ASP.NET MVC

If you don't need a controller or action level exception handling, you can do the error handling in the Application_Error event. You can turn off custom errors in the web.config and do the logging and error handling in this event (including the redirection to the correct page).

Something similar to that:

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

    HttpException httpException = exception as HttpException;  

    string action = string.Empty;    

    if (httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                // page not found 
                action = "NotFound";
                break;
            //TODO: handle other codes
            default:
                action = "general-error";
                break;
        }
    }
    else
    {
        //TODO: Define action for other exception types
        action = "general-error";
    }

    Server.ClearError();

    string culture = Thread.CurrentThread.CurrentCulture.Name;    

    Exception exception = Server.GetLastError();
    Response.Redirect(String.Format("~/{0}/error/{1}", culture, action));
}

Upvotes: 1

Related Questions