我正在使用ASP.NET MVC3
和运行网站Windows Server 2003
。我试图弄清楚如何处理所有 HTTP 错误。我已经实现了代码,但是当返回 404 错误时,有时会在浏览器中显示 403 错误。
这是我实现的代码:
在我的global.asax.cs
:
protected void Application_Error(object sender, EventArgs e)
{
MvcApplication app = (MvcApplication)sender;
HttpContext context = app.Context;
Exception exception = app.Server.GetLastError();
context.Response.Clear();
context.ClearError();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "Index";
routeData.Values["httpException"] = httpException;
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
ErrorController.cs
文件:
public class ErrorController : Controller
{
public ActionResult Index()
{
ErrorModel model = new ErrorModel();
HttpException httpException = RouteData.Values["httpException"] as HttpException;
int httpCode = (httpException == null) ? 500 : httpException.GetHttpCode();
switch (httpCode)
{
case 403:
//Response.StatusCode = 403;
model.Heading = "Forbidden";
model.Message = "You aren't authorised to access this page.";
break;
case 404:
//Response.StatusCode = 404;
model.Heading = "Page not found";
model.Message = "We couldn't find the page you requested.";
break;
case 500:
default:
Response.StatusCode = 500;
model.Heading = "Error";
model.Message = "Sorry, something went wrong. It's been logged.";
break;
}
Response.TrySkipIisCustomErrors = true;
return View(model);
}
}
我的 web.config 中没有设置任何内容。
我希望它在用户尝试访问我的目录(例如app_code
和类似目录)时显示正确的错误。这可能吗?
当我输入http://localhost:43596/app_code
然后我看到它似乎是一个 404 错误,但它显示 IE 的默认 403 错误页面。如何让我的代码显示正确的 HTTP 错误消息?
我想要这种方式的原因是因为如果用户试图以任何方式破坏网站,我需要记录所有尝试。我希望能够看到谁在做错误的访问。