我关注了这篇文章并创建了一个全局错误处理程序。我自己添加了处理 404 错误。但是,当我在本地测试时它工作正常,但一旦部署到 Web 服务器,我的自定义消息就不再显示了。相反,出现了默认的丑陋的。
在远程调试中,我可以跟踪执行,它确实得到了我的自定义 404 错误操作,但不知何故,IIS 在某个时候接管了。
在我的 Global.asax.cs 中,我有:
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"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
然后在我的 ErrorHandler.cs 中,我有:
public ActionResult General(Exception exception)
{
// log error
return Content("General error", "text/html");
}
public ActionResult Http403(Exception exception)
{
return Content("Forbidden", "text/plain");
}
public ActionResult Http404(Exception exception)
{
return Content("Page not found.", "text/plain"); // this displays when tested locally, but not after deployed to web server.
}
}