Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error pages in different areas in ASP.NET MVC3

I have set up custom error pages on my site using

<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
  <error statusCode="500" redirect="~/Error/InternalError"/>
  <error statusCode="404" redirect="~/Error/FileNotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

however there is another area on the site, Suppliers, and when an error occurs in the supplier area the redirect goes to Suppliers/Error/_. Since I don't have any error pages here, the site just seems to hang never shows the error pages. How can I fix this without having to copy the error pages to the supplier area?

like image 482
Jordan Wallwork Avatar asked Aug 30 '11 12:08

Jordan Wallwork


Video Answer


1 Answers

As far as I understand with MVC your URL make up, by default is:

Domain/Controller/Action/id

If you have an "Error" Controller. In your logic, you test to see if the request originated from an user of the site that would need to redirect to the "Suppliers" Error page

 [HandleError]
    public ActionResult Index()
    {
        // Test to see if you need to go to the SuppliersController
        if (this.User.IsInRole("supplier"))
        {
            return Redirect("/Suppliers/Error");
        }
        else
        {
            return View(); // This returns the "Error" View from the shared folder
        }
    }

redirect to an Error handling action on your Suppliers Controller that will return the right view.

public class SuppliersController : Controller
{
    //
    // GET: /Suppliers/

    public ActionResult Error()
    {
        return View("Error","SomeMasterPage"); // No "Error" view in Suppliers View folder, so it uses the one in shared folder
    }

}

You can also use the [Authorize] attribute on your Suppliers Error Action to make sure the user is logged on.

In this way, you will get your desired /Suppliers/Error URL and can use the SuppliersController Action to specify the desired view, model, and master/Layout page.

also look at this very comprehensive reply to a similar question:

Best 404 example I can find for mvc

like image 146
Timtek Avatar answered Oct 11 '22 03:10

Timtek