Can't get defaultRedirect to work

2019-02-08 19:41发布

问题:

In my web.config, I have:

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

In Views/Shared/Error.cshtml, I have:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

回答1:

The defaultRedirect won't go directly to a view. Your defaultRedirect looks like a razor view file which it can't process. For example: Where does it get the model from? It isn't, and can't, be specified in the config file so it can't process a view.

If you want more dynamic error pages in MVC you might want to read custom error pages and error handling in MVC 3



回答2:

It works for me. Just make this change in web.config:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Views/Shared/Error.cshtml">
    </customErrors>
</system.web>


回答3:

Edit you web.config as:

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

If you use asp.net mvc 1.0 or 2.0, you should add HandleError attribute for each controller:

[HandleError]
public class HomeController: Controller
{
    public ActionResult Error()
    {
        return View();
    }
}

if you use asp.net mvc 3.0:

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            GlobalFilters.Filters.Add(new HandleErrorAttribute());
        }
}


回答4:

You should mark your controller action with [HandleError] attribute or register it as a global filter

EDIT: It happens because of custom errors' redirects functionality belongs to ASP.NET infrastructure and knows nothing about ASP.NET MVC.

You should create separate controller for managing redirects and specify url to it in your Web.config. Or you could create static html file and put it into root directory (or wherever else except Views directory)



回答5:

One solution is create ErrorController

public class ErrorController : Controller
{
    //
    // GET: /Error/

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

    public ActionResult Error404()
    {
        return View("Error");
    }

}

Change Web.config