我正在尝试正确处理并为此URL返回404:http://localhost:2867/dd./xml(注意斜杠前的点)
在我当前的实现中,我在Application_Error中得到4个异常/错误。 Server.GetLastError()返回的第一个异常为System.Web.HttpException,而后三个为空。
我做了一个最小的实现来重现此问题。这是global.asax.cs中的代码:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Generic");
routeData.Values.Add("area", "");
IController errorController = new ErrorController();
// this line throws System.Web.HttpException is a view is returned from ErrorController
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
错误 Controller 如下所示:
public class ErrorController : Controller
{
public ActionResult Generic()
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View();
// returning content rather than a View doesn't fire 'System.Web.HttpException' in Application_Error
//return Content("Some error!");
}
}
有两个问题。一个是给定URL的错误,而不是Application_Error中的一个错误,我得到3或4,另一个是从ErrorController返回 View 时,在Application_Start的Execute调用行上引发了异常。如果返回Content(“something”),则不会触发此内部(我认为是MVC)异常。
为了查看问题,您必须处于 Debug模式并使用开发服务器。使用IIS或IIS Express时,由于某些原因未捕获到错误。同样,这些错误有时也会消失。为了使它重新开始,您必须清洁溶液。
如果您想使用它,这里是最低限度的解决方案:http://dl.dropbox.com/u/16605600/InvalidUrl.zip
感谢您的帮助!
最佳答案
如果您使用的是IIS7 +,则可以将其放入web.config中:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />
</httpErrors>
</system.webServer>
(来自How can I properly handle 404 in ASP.NET MVC?的答案)
知道Application_Error中发生了什么仍然很高兴。
关于asp.net-mvc-3 - ASP.NET MVC正确处理无效的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8187109/