如何从所有控制器捕获 Web 配置中的所有异常 C#

How to catch all exceptions in web config from all controllers c#

我们正在使用 MVC 结构并且有多个 c# 控制器,是否可以通过 web.config 捕获它们?而不是向所有控制器方法添加 catch 语句?

非常感谢。

您可以创建自己的基础控制器并处理 OnException 事件中的异常。

public class BaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
       // to do : Log the exception (filterContext.Exception)
       // and redirect / return error view
        filterContext.ExceptionHandled = true;
        // If the exception occurred in an ajax call. Send a json response back
        // (you need to parse this and display to user as needed at client side)
        if (filterContext.HttpContext.Request.Headers["X-Requested-With"]
                                                          =="XMLHttpRequest")
        {
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { Error = true, Message = filterContext.Exception.Message }
            };
            filterContext.HttpContext.Response.StatusCode = 500; // Set as needed
        }
        else
        {
            filterContext.Result = new ViewResult { ViewName = "Error.cshtml" }; 
            //Assuming the view exists in the "~/Views/Shared" folder
        }
    }
}

对于非 ajax 请求,它将向用户呈现 Error.cshtml。如果您想重定向(一个新的 GET 调用)到您的 Error 操作方法而不是显示 Error.cshtml,您可以将 ViewResult 替换为 RedirectToRouteResult

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
                                               {"controller", "Home"}, {"action", "Error"}
                                              };

现在让你的其他控制器继承这个

public class HomeController : BaseController 
{
   public ActionResult Die()
   {
      throw new Exception("Bad code!");
   }
}
public class ProductsController : BaseController 
{
   public ActionResult Index()
   {
       var arr =new int[2];
       var thisShouldCrash = arr[10];
       return View();
   }
}