在ASP.NET MVC 5中发生任何错误时重定向到控制器操作

时间:2015-09-07 19:04:37

标签: c# asp.net error-handling asp.net-mvc-5

发生错误时,我需要重定向到某个页面。

web.config

<customErrors mode="On" defaultRedirect="~/Error/Index">
</customErrors>

ErrorController.cs

public class ErrorController : BaseController
{
    // GET: Error
    public ActionResult Index(string aspxerrorpath)
    {
        SendMail("Error Web", string.Format("Usuario: {0} .Error en: {1}", UserLogged == null ? "" : UserLogged.FullName(), aspxerrorpath));
        return View("StringData","Se ha producido un error. Intentalo pasado unos minutos o envia un aviso al administrador desde el apartado de sugerencias");
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

在Global.asax.cs中添加以下内容的简单方法:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    // Log the exception.
    logger.Error(exception);
    Response.Clear();
    Context.Response.Redirect("~/"); // it will redirect to just main page of your site. Replace this line to redirect whatever you need.
}

这方面的好方法是另外对HttpException强制转换异常,然后根据这样处理异常:

HttpException httpException = exception as HttpException;
if (httpException == null)
{
  // should redirect to common error page
}
else //It's an Http Exception, Let's handle it.
{
    switch (httpException.GetHttpCode())
    {
      case 404:
        // Page not found.
        // redirect to another error page if need
        break;
      case 500:
        // Server error.
        // redirect to another error page if need
        break;
      default: // covers all other http errors
        // redirect to another error page if need
        break;
    }
}