您可以通过在 Global.asax 中注册 Application_Error 事件来做到这一点,然后以这种方式将其重定向到带有数据的错误控制器,或者您可以根据错误代码执行您想要的任何功能
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "oops";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "NoAccess";
break;
case 404:
routeData.Values["action"] = "NotFound";
break;
}
}
IController errorsController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorsController.Execute(rc);
}
然后用 oops / NotAccess / NotFound 之类的动作制作一个控制器
public ActionResult oops(Exception exception)
{
//return Content("General failure", "text/plain");
// return View();
}
public ActionResult NotFound()
{
// return Content("Not found", "text/plain");
// return View("oops");
}
public ActionResult NoAccess()
{
//return Content("Forbidden", "text/plain");
//return View("oops");
}
并用适当的信息返回您自己的观点