我一直在寻找可以根据应用程序中的异常自定义错误页面的文章。我尝试了以下方法
public class ErrorController : Controller
{
public ActionResult Index(int status, Exception error)
{
Response.StatusCode = status;
ViewBag.status = status;
return View(status);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
全球.asax
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 trialerror.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");
}
}
索引.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<html>
<head>
<title> Error</title>
</head>
<body>
<div>
@{
int x=ViewBag.status;
}
<p style=" color: Red;">
@switch (x) {
case 401: {
<span>PAGE NOT FOUND</span>
}
break;
case 403: {
<span>FORBIDDEN</span>
}
break;
case 404: {
<span>We have experienced a 404 error.Site temporarily down</span>
}
break;
case 500: {
<span>please refresh page and try again!</span>
}
break;
//and more cases for more error-codes...
default: {
<span>Unknown error!!!</span>
}
break;
}
</p>
</div>
</body>
</html>
该代码可以为案例中的所有错误提供自定义页面。但是现在我想从 try -catch 方法中捕获所有异常,例如 db 异常并以自定义方式显示它。
示例:“空值异常或连接字符串异常”。
我的疑问是我怎么能为此提供一些东西。我不知道继续吗?