首先,快速了解我想要实现的目标:将特定异常转换为 HTTP 404,以便 ASP.NET 可以进一步处理它。
我正在以这种方式处理 ASP.NET (MVC2) 中的异常:
protected void Application_Error(object sender, EventArgs e) {
var err = Server.GetLastError();
if (err == null)
return;
err = err.GetBaseException();
var noObject = err as ObjectNotFoundException;
if (noObject != null)
HandleObjectNotFound();
var handled = noObject != null;
if (!handled)
Logger.Fatal("Unhandled exception has occured in application.", err);
}
private void HandleObjectNotFound() {
Server.ClearError();
Response.Clear();
// new HttpExcepton(404, "Not Found"); // Throw or not to throw?
Response.StatusCode = 404;
Response.StatusDescription = "Not Found";
Response.StatusDescription = "Not Found";
Response.Write("The whole HTML body explaining whata 404 is??");
}
问题是我无法配置默认值customErrors
来使用它。如果是,on
那么它永远不会重定向到customErrors
:中指定的页面<error statusCode="404" redirect="404.html"/>
。
我也尝试new HttpExcepton(404, "Not Found")
从处理程序中提出,但是响应代码是200
我不明白的原因。
所以问题是:
AnException
转换为 HTTP404
响应的正确方法是什么?customErrors
在 Application_Error 中处理异常时,部分如何工作?- 为什么抛出 HttpException(404) 会以成功 (200) 状态呈现(空白)页面?
谢谢,
德米特里。