2

我正在尝试正确处理并返回此 URL 的 404:http://localhost:2867/dd./xml(注意斜杠前的点)

在我当前的实现中,我在 Application_Error 中得到 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

感谢您的帮助!

4

2 回答 2

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>

(来自如何在 ASP.NET MVC 中正确处理 404 的答案? )

仍然很高兴知道 Application_Error 中发生了什么。

于 2011-11-19T01:14:41.500 回答
0

您可以通过更改customeErrorsweb.config 中的部分
来处理 404 还有一个redirectMode属性可用于控制错误页面重定向的性质(并避免 302)(阅读此处

<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.oneexception.aspx

于 2011-11-18T18:27:19.043 回答