开发者

Errors with custom HandleErrorAttribute does not work

I've read many articles and several post (including here in stackoverflow) but do not know what I'm doing wrong.

Here my code:

Global.asax.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

ErrorControler.cs

public class ErrorController : Controller
{
    public ActionResult Error404()
    {
        return View();
    }

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

Web.config

<customErro开发者_如何学JAVArs mode="On" defaultRedirect="~/Error/Error500">
  <error statusCode="404" redirect="~/Error/Error404"/>
</customErrors>

MyController.cs

public ActionResult Index()
{
    using (var db = new DataContext())
    {
        int a = 2, b = 0;
        var r = a / b;
        return View(r);
    }
}

Error500.cshtml

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Erro";
}

<h2>@ViewBag.Title</h2>
<div id="error-info">
    <p>Ocorreu um erro inexperado na página <a class="error-url" href="@Response["aspxerrorpath"]" title="Origem do erro">@Response["aspxerrorpath"]</a></p>
    <p>Se o erro persistir, por-favor, entre em contato com os administradores do site.</p>
    <div class="error-details">
        <p>@Model.Exception.Message</p>
    </div>
</div>

When I try to access the path /MyController the following message appears:

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/Error500

I would like that happen when an error on any controller, if the http status code has not been informed in web.config, it redirects to the default view Error500

In this article, for example, it handles DbException errors, but would like to handle any type of error.

Errors of type 404 (page not found) works perfectly. The user is redirected to the page Error404.cshtml


If you want this to happen remove/comment the following line from your Global.asax:

filters.Add(new HandleErrorAttribute());

You basically have to choose whether you want ASP.NET to handle your errors (the <customErrors> section in your web.config) or ASp.NET MVC (the global HandleErrorAttribute action filter, which by the way requires you to turn on custom errors in web.config)

Or checkout an alternative method for handling errors in ASP.NET MVC (with this approach you still have to remove the line I showed from your Global.asax).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜