3

我已经在我的项目中实现了自定义错误功能,它可以在本地 IIS 上运行,但不能在实时服务器上运行。我已经使用 Global.asax 文件实现了这个功能,并且我在 MVC 的自定义错误控制器中调用了我的自定义错误操作方法。我已经在本地 IIS 上发布并运行,它运行良好,但在实时服务器上。

我的 Global.asax.cs 文件

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    //do not register HandleErrorAttribute. use classic error handling mode
    filters.Add(new HandleErrorAttribute());
}

protected void Application_Error(Object sender, EventArgs e)
{
    LogException(Server.GetLastError());

    CustomErrorsSection customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors");
    string defaultRedirect = customErrorsSection.DefaultRedirect;
    if (customErrorsSection.Mod e== CustomErrorsMode.On)
    {
        var ex = Server.GetLastError().GetBaseException();

        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values.Add("controller", "Common");
        routeData.Values.Add("action", "CustomError");

        if (ex is HttpException)
        {
            var httpException = (HttpException)ex;
            var code = httpException.GetHttpCode();
            routeData.Values.Add("status", code);
        }
        else
        {
            routeData.Values.Add("status", 500);
        }

        routeData.Values.Add("error", ex);

        IController errorController = new Test.Controllers.CommonController();
        errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    }
}

我的自定义错误控制器及其操作方法

public ActionResult CustomError(int status, Exception error)
{
    var model = new CustomErrorModel();
    model.Code = status;
    model.Description = Convert.ToString(error);
    Response.StatusCode = status;
    return View(model);
}

所以我该怎么做?

4

2 回答 2

7

I had this problem where errors on live IIS server weren't showing custom error pages (which return proper HttpStatusCodes) but it WAS working on local IIS (localhost address using default website - not Cassini). They should have worked exactly the same I would have thought - anyway this web.config setting fixed it.

<configuration>
    <system.webServer>
        <httpErrors existingResponse="PassThrough"></httpErrors>
    </system.webServer>
</configuration>

Note that my setup uses Application_Error in global.asax and just this other web.config setting:

<customErrors mode="On">
    <!-- There is custom handling of errors in Global.asax -->
</customErrors>
于 2013-07-04T06:58:36.507 回答
1

2 种方法

路由方法

// We couldn't find a route to handle the request. Show the 404 page. 
routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "CustomError" } );

或者

Web.config 中的自定义错误处理程序

<customErrors mode="On" >
    <error statusCode="404" redirect="~/CatchallController/CustomError" />
</customErrors>   

没有路由匹配引发的条件是 404。这样你就可以将所有不匹配的~/CatchallController/CustomError

于 2013-01-24T05:37:42.997 回答