【问题标题】:Using different 404 error pages depending on URL tried by the user根据用户尝试的 URL 使用不同的 404 错误页面
【发布时间】:2014-10-26 10:44:12
【问题描述】:

(注意:我是asp.net/c#的新手,请多多包涵)

在我的网站上,我在 web.config 中使用了自定义 404 错误页面

<customErrors mode="RemoteOnly" defaultRedirect="http://mywebsite.org/404">
  <error statusCode="404" redirect="http://mywebsite.org/404" />
</customErrors>

现在我想添加额外的 404 页面,这些页面由包含某些字符串的 URL “触发”。例如,如果 URL 包含 /library/,我希望将用户重定向到 http://mywebsite.org/library-404,其中包含特定于网站库部分的信息。包含 /services/ 等的 URL 也是如此。

这可以吗?如果是这样,怎么做?感谢您的宝贵时间。

【问题讨论】:

    标签: c# asp.net redirect web-config http-status-code-404


    【解决方案1】:

    您可以尝试使用ASP.NET MVC。设置路由来映射Url。

    【讨论】:

    • 您能否举例说明如何将路由映射设置为 URL?就目前而言,这更像是一个评论而不是一个答案。
    【解决方案2】:

    您可以在Global.asax.cs中定义方法Application_Error并像这样处理

    void Application_Error(object sender, EventArgs e)
    {
        var error = Server.GetLastError();
        var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;
        string path = Request.Path;
    
        if (code == 404)
        {
            if (new Regex(@"\/library\/", RegexOptions.IgnoreCase).IsMatch(path))
            {
                Server.ClearError();
                Response.Redirect(String.Format("~/Library/Error404"));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 2012-07-26
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      相关资源
      最近更新 更多