我試圖妥善處理,並返回404這個網址:http://localhost:2867/dd./xml(注意斜線前的點)ASP.NET MVC妥善處理無效的網址
在我目前的實現我得到了4個異常/錯誤應用程序錯誤。 Server.GetLastError()返回的第一個異常是System.Web.HttpException,而接下來的三個是null。
我做了一個最低限度的實施來重現這個問題。下面是的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));
}
誤差控制器看起來是這樣的:
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返回視圖時,Application_Start中的Execute調用行上拋出異常。如果返回一個Content(「something」),而不是這個內部(對於MVC,我假設)異常不會被觸發。
爲了看到問題,您必須處於調試模式並使用開發服務器。在使用IIS或IIS Express時,出於某種原因不會捕獲錯誤。此外,每隔不久這些錯誤就會消失。爲了回到起點,你必須清理解決方案。
如果你想用它玩,這裏的最低限度的解決方案:http://dl.dropbox.com/u/16605600/InvalidUrl.zip
謝謝您的幫助!
如果我沒有錯誤的工作,重定向到不正確的方式返回http錯誤的不同頁面。 – pbz
此外,此代碼用於404s旁邊的其他應用程序錯誤。我專注於404只是爲了表明一些奇怪的事情正在發生。 – pbz
@pbz asp.net錯誤處理將自動應用正確的錯誤狀態代碼,我不完全清楚爲什麼它不適合重定向到不同的頁面(雖然我的http有點生疏,但...)其他錯誤可以用500代碼處理,我還會在OnException控制器方法上添加細節。 – TJB