26

我正在尝试为我的 Web 应用程序设置自定义 404 错误页面。问题是这个应用程序将被部署到许多不同的环境中。有时它会在虚拟目录中,有时则不会。

我在一个名为 ErrorPages 的目录中有错误页面,并设置了我的配置,如下所示:

   <httpErrors errorMode="Custom" existingResponse="Replace">
     <remove statusCode="404"/>
     <error statusCode="404" path="/VirtualDir/ErrorPages/404.aspx" responseMode="ExecuteURL" />
   </httpErrors>
</system.webServer>

问题是当我将它部署到网站的根目录时,/VirtualDir需要删除该部分。如果我在部署之前将其删除,那么我需要在部署到虚拟目录时将其重新添加。有什么方法可以将路径设置为相对于虚拟目录而不是站点?

我尝试过使用 a ~,但这也不起作用,如下所示:

   <httpErrors errorMode="Custom" existingResponse="Replace">
     <remove statusCode="404"/>
     <error statusCode="404" path="~/ErrorPages/404.aspx" responseMode="ExecuteURL" />
   </httpErrors>
</system.webServer>
4

2 回答 2

4

您可以使用web.config转换来设置每个环境的路径:

网络配置

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <error statusCode="404" path="/VirtualDir/ErrorPages/404.aspx" responseMode="ExecuteURL" />
</httpErrors>

web.Release.config

<httpErrors>
  <error statusCode="404" path="/ErrorPages/404.aspx" responseMode="ExecuteURL" />
</httpErrors>
于 2012-10-05T12:53:23.377 回答
2

我遇到了类似的问题,所以我使用服务器端代码通过动态生成的 URL(有或没有虚拟目录)重定向到 CustomError 页面,尽管 ~/ 成功地从这里重定向到正确的路径。

当应用程序 Application_Error 发生错误并最终触发此代码块时:

if (App.Configuration.DebugMode == DebugModes.ApplicationErrorMessage)
{                    
    string stockMessage = App.Configuration.ApplicationErrorMessage;

    // Handle some stock errors that may require special error pages
    HttpException httpException = serverException as HttpException;
    if (httpException != null)
    {
        int HttpCode = httpException.GetHttpCode();
        Server.ClearError();

        if (HttpCode == 404) // Page Not Found 
        {
            Response.StatusCode = 404;
            Response.Redirect("~/ErrorPage.aspx"); // ~ works fine no matter site is in Virtual Directory or Web Site
            return;
        }
    }

    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = 404;
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

无需在 web.config 的 httpErrors 部分中编写页面路径,您可以创建应用设置并在那里保存路径。在后面的代码中,您可以从应用设置和重定向中获取路径,如上所述。

我找到了另一个类似的链接,他比我解释得更好,所以尽管去吧 http://labs.episerver.com/en/Blogs/Ted-Nyberg/Dates/112276/2/Programmatically-configure-customErrors-redirects/

于 2012-05-07T11:23:40.987 回答