【问题标题】:IIS showing server error instead of custom errorsIIS 显示服务器错误而不是自定义错误
【发布时间】:2014-10-19 05:59:55
【问题描述】:

我正在使用 MVC 5,我正在使用自定义视图处理错误,例如(404、403.. 等) 它在我的本地 IIS 上运行良好,但是当我在 临时服务器 上发布时,它会显示有关这些错误代码的 IIS 服务器错误消息。

它正在显示这条消息:

代替:

我已将web.config 修改为<customErrors mode="Off" />

Global.asax

        if ((Context.Server.GetLastError() is UnauthorizedAccessException))
        {
            log.LogError(Context.Server.GetLastError().Message, Context.Server.GetLastError());
            customErrorPage = @"~/Error/?id=403"; //security
        }
        else if ((Context.Server.GetLastError() is HttpException) && (((HttpException)Context.Server.GetLastError()).GetHttpCode() == 404))
        {
            //** Handle 404 error and response code
            log.LogError("404", Context.Server.GetLastError());
            customErrorPage = @"~/Error/?id=404";
        }
        else
        {
            log.LogError(Context.Server.GetLastError().Message, Context.Server.GetLastError());
            customErrorPage = @"~/Error";
        }

        if (ConfigurationHelper.Common.ShowCustomErrorPage)
        {
            var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
            Response.Redirect(urlHelper.Content(customErrorPage), false);
            Server.ClearError();
        }

错误控制器:

    public ActionResult Index(string id)
    {
        if (!string.IsNullOrEmpty(id) && id.Equals("404"))
        {
            Response.StatusCode = 404;
            return !Request.IsAjaxRequest() ? (ActionResult)View("404") : PartialView("404");
        }
        if (!string.IsNullOrEmpty(id) && id.ToLower().Equals("403"))
        {
            Response.StatusCode = 403;
            return !Request.IsAjaxRequest() ? (ActionResult)View("Security") : PartialView("Security");
        }
        return !Request.IsAjaxRequest() ? (ActionResult)View("Index") : PartialView("Index");
    }

我应该怎么做才能显示我的自定义错误消息?

【问题讨论】:

    标签: asp.net-mvc iis server-error


    【解决方案1】:

    只需添加如下web.config配置即可通过IIS默认错误处理行为

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

    【讨论】:

    • 这很好用,但它会完全删除 IIS 级别 404 错误处理。如果你有一个未被 ASP.NET 引擎处理的 URL,它不会返回 404 not found 错误。
    【解决方案2】:

    尝试使用

    Response.TrySkipIisCustomErrors = true;
    

    在您的控制器上。 比那个好

    <httpErrors existingResponse="PassThrough" />
    

    因为PassThrough 可能会导致一些您并不总是期望的结果。例如阅读here 如果模块没有设置任何文本,它将如何使自定义错误模块返回空白响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      相关资源
      最近更新 更多