c# - ASP.NET MVC 5中发生任何错误时,重定向到 Controller 操作

标签 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

最佳答案

在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;
    }
}

关于c# - ASP.NET MVC 5中发生任何错误时,重定向到 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444726/

相关文章:

c# - 在 QueryExpression 中包含 OptionSetValue

c# - 使用 Linq 在值之间添加逗号

c# - 我怎样才能去掉 Picturebox 的边框?

c# - 以编程方式创建图像并将其作为字节 [] 数据从 Web 服务检索为媒体项存储在 Umbraco 中

asp.net - 用户在我的网站上点击确认后如何确认 Paypal express 付款?

node.js - 如何处理内部服务器 API 和 HTTP API 之间的错误

java - 如何在ANTLR4中实现错误处理

c# - 如何获取由空格分隔的字符串的第一部分和最后一部分

javascript - 如何使一个选择选项更改另一个选择中的选项

error-handling - 无效的所有者或用户错误