我们正在使用MVC Structure并拥有多个c#控制器,是否有可能通过web.config捕获它们?而不是向所有控制器方法添加一个catch语句?
非常感谢你。
答案 0 :(得分:0)
您可以创建自己的基本控制器并处理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
呈现给用户。如果您要对Error
操作方法进行重定向(新的GET调用)而不是显示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();
}
}