You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精准捕获404与500错误?求代码具体放置位置

Hey there! Let’s get your 404 and 500 error handling sorted out using your preferred tools—global.asax and web.config—since you’re on IIS 8 which plays nicely with these approaches. I’ll break down exactly where to put the code and why your previous attempts might have failed.

Web.Config Solution (IIS 8+)

This is your simplest option, but the key is placing the code in the correct hierarchy within your root web.config (the one in your project’s root folder, not a subfolder). Here’s the full setup:

1. <system.web> Section (Handles ASP.NET Dynamic Errors)

Add this directly inside the root <configuration> node (alongside sections like <appSettings> or <connectionStrings>):

<system.web>
  <customErrors mode="On" defaultRedirect="~/Error/500" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="~/Error/404" />
    <error statusCode="500" redirect="~/Error/500" />
  </customErrors>
</system.web>
  • mode="On": Ensures errors are redirected even when testing locally (if you used RemoteOnly, you wouldn’t see errors on your dev machine)
  • redirectMode="ResponseRewrite": Keeps the original error URL in the browser bar (better for SEO and user experience than a full redirect)

2. <system.webServer> Section (Handles Static File Errors)

This catches missing static files (like a non-existent .html or .css) that the <system.web> section won’t pick up. Add this also inside the root <configuration> node:

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <remove statusCode="500" subStatusCode="-1" />
    <error statusCode="404" path="/Error/404" responseMode="ExecuteURL" />
    <error statusCode="500" path="/Error/500" responseMode="ExecuteURL" />
  </httpErrors>
</system.webServer>
  • existingResponse="Replace": Tells IIS to override any default error pages
  • responseMode="ExecuteURL": Runs your custom error page without changing the URL

Required Error Controller & Routes

You’ll need an ErrorController to serve the error views, plus route mappings. Here’s the controller code:

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View(); // Make sure you have a NotFound.cshtml view
    }

    public ActionResult ServerError()
    {
        Response.StatusCode = 500;
        return View(); // Make sure you have a ServerError.cshtml view
    }
}

And add these routes to your RouteConfig.cs:

routes.MapRoute(
    name: "Error404",
    url: "Error/404",
    defaults: new { controller = "Error", action = "NotFound" }
);

routes.MapRoute(
    name: "Error500",
    url: "Error/500",
    defaults: new { controller = "Error", action = "ServerError" }
);

Global.asax Solution

If you’d rather handle errors via code, here’s how to fix your global.asax.cs setup to catch both 404 and 500 errors:

1. Application_Error (Catches Unhandled Exceptions = 500 Errors)

This method fires whenever an unhandled exception occurs. Make sure you include Server.ClearError() to stop IIS from showing its default page:

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;

    // Clear the error so IIS doesn't override your custom page
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values["controller"] = "Error";

    if (httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values["action"] = "NotFound";
                Response.StatusCode = 404;
                break;
            case 500:
                routeData.Values["action"] = "ServerError";
                Response.StatusCode = 500;
                break;
            default:
                routeData.Values["action"] = "ServerError";
                Response.StatusCode = 500;
                break;
        }
    }
    else
    {
        // Non-HTTP exceptions (like null references) count as 500 errors
        routeData.Values["action"] = "ServerError";
        Response.StatusCode = 500;
    }

    // Execute the error controller action
    var errorController = new ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

2. Application_EndRequest (Catches 404s Missed by Application_Error)

Some 404s (like invalid routes that never hit a controller) won’t trigger Application_Error, so add this to catch them:

protected void Application_EndRequest()
{
    if (Response.StatusCode == 404 && !Response.IsRequestBeingRedirected)
    {
        Server.ClearError();
        Response.RedirectToRoute("Error404");
    }
}

Note: This relies on the Error404 route we defined earlier in RouteConfig.cs.


Why Your Previous Attempts Failed

  • Web.Config: You probably placed the code in the wrong section (not directly under <configuration>) or used mode="RemoteOnly" which hides errors locally.
  • Global.asax: You might have forgotten to call Server.ClearError() (which lets IIS show its default page instead of yours) or didn’t set the Response.StatusCode correctly.

内容的提问来源于stack exchange,提问作者Bradley William Elko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:02:14