更新时间:2023-01-10 09:32:26
我使用这些步骤: / p>
I use these steps:
// in Global.asax.cs:
protected void Application_Error(object sender, EventArgs e) {
var ex = Server.GetLastError().GetBaseException();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
if (ex.GetType() == typeof(HttpException)) {
var httpException = (HttpException)ex;
var code = httpException.GetHttpCode();
routeData.Values.Add("status", code);
} else {
routeData.Values.Add("status", 500);
}
routeData.Values.Add("error", ex);
IController errorController = new Kavand.Web.Controllers.ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
protected void Application_EndRequest(object sender, EventArgs e) {
if (Context.Response.StatusCode == 401) { // this is important, because the 401 is not an error by default!!!
throw new HttpException(401, "You are not authorised");
}
}
AND:
// in Error Controller:
public class ErrorController : Controller {
public ActionResult Index(int status, Exception error) {
Response.StatusCode = status;
return View(status);
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
}
}
和错误文件夹中的索引视图:
AND the index view in Error folder:
@* in ~/Views/Error/Index.cshtml: *@
@model Int32
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Kavand | Error</title>
</head>
<body>
<div>
There was an error with your request. The error is:<br />
<p style=" color: Red;">
@switch (Model) {
case 401: {
<span>Your message goes here...</span>
}
break;
case 403: {
<span>Your message goes here...</span>
}
break;
case 404: {
<span>Your message goes here...</span>
}
break;
case 500: {
<span>Your message goes here...</span>
}
break;
//and more cases for more error-codes...
default: {
<span>Unknown error!!!</span>
}
break;
}
</p>
</div>
</body>
</html>
AND - 最后一步:
AND -the final step:
<!-- in web.config: -->
<customErrors mode="Off"/>