2

我試圖妥善處理,並返回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

謝謝您的幫助!

回答

1

如果您使用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中。

0

您可以通過在web.config改變customeErrors部分處理404
還有一個redirectMode attribute,你可以用它來控制錯誤頁面重定向的性質(和避免302)(閱讀here

<configuration> 
    ... 
    <system.web> 
    <customErrors mode="RemoteOnly" 
        redirectMode="ResponseRewrite" 
        defaultRedirect="/ErrorPages/Oops.aspx"> 
     <error statusCode="404" redirect="/ErrorPages/404.aspx" /> 
    </customErrors> 
... 

http://www.asp.net/hosting/tutorials/displaying-a-custom-error-page-cs

在ASP.net MVC,還有一個方法,你可以覆蓋到漁獲交流拋出的所有異常控制器。只需覆蓋Controller.OnException(...),您也可以在那裏自定義錯誤處理。如果所有的控制器都從一個通用的基礎控制器類繼承,那麼可以將錯誤處理放在那裏。

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx

+0

如果我沒有錯誤的工作,重定向到不正確的方式返回http錯誤的不同頁面。 – pbz

+0

此外,此代碼用於404s旁邊的其他應用程序錯誤。我專注於404只是爲了表明一些奇怪的事情正在發生。 – pbz

+0

@pbz asp.net錯誤處理將自動應用正確的錯誤狀態代碼,我不完全清楚爲什麼它不適合重定向到不同的頁面(雖然我的http有點生疏,但...)其他錯誤可以用500代碼處理,我還會在OnException控制器方法上添加細節。 – TJB