【问题标题】:How to redirect any url that have hyphens to home url in asp.net mvc 5如何将任何带有连字符的网址重定向到asp.net mvc 5中的主页网址
【发布时间】:2016-08-24 05:43:37
【问题描述】:

我正在为我的一位客户创建一个新网站。他们的旧网站是使用 wordpress 开发的,因此它有 100 个损坏的网址,如下所示:

http://www.example.com/best-gym-in-town/
http://www.example.com/video-gallery/
http://www.example.com/fun-stuff/
http://www.example.com/are-you-a-diabetes-patient/
http://www.example.com/john-in-media/
http://www.example.com/photo-gallery/
http://www.example.com/nutrition-program-that-suits-your-lifestyl/
http://www.example.com/our-range-of-fitness-tests/
http://www.example.com/corporate-group-workshops/some-article/another-article

我正在 asp.net mvc 5 中开发新站点。我想在 web.config 中编写一个 httpRedirect 规则,可以将上述任何 URL 重定向到主页或任何特定页面。

到目前为止,这就是我对解决方案的看法

<location path="about-me">
<system.webServer>
        <httpRedirect enabled="true" destination="/home"
         httpResponseStatus="Permanent" />
</system.webServer>
</location>

但我必须在 web.config 中编写 100 条这样的条目。我正在寻找更好更高效的替代方案

【问题讨论】:

    标签: iis asp.net-mvc-5 web-config


    【解决方案1】:

    在 Global.asax 中,钩入Application_BeginRequest 方法并从那里重定向到主页

    protected void Application_BeginRequest(object sender, EventArgs e)
    {     
        try
        {
            if (HttpContext.Current.Request.Url.AbsolutePath.Contains("-")){
                HttpContext.Current.Response.RedirectPermanent("/");
            }
        }
        catch (ThreadAbortException){}
    }
    

    或者,您可以改为挂钩到 Global.asax 中的 Application_Error 方法并从那里检测 404

    protected void Application_Error(Object sender, EventArgs e)
    {    
        var exception = Server.GetLastError();   
    
        if (exception != null && exception == 404)
        {    
            try
                {
                Response.Clear();
                Server.ClearError();
                Response.Redirect("/");    
                }
            }
            catch (ThreadAbortException){}
        }
    }
    

    【讨论】:

    • 我将尝试挂钩 beginrequest 事件并进行测试。谢谢你的建议。我仍然会尝试寻找基于配置的方法。
    • 如果您想获得更高级的信息,您可以添加针对数据库/配置的查找,该数据库/配置具有旧网址到新网址的映射。
    • np,如果它解决了问题,不要忘记接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-10-18
    • 2011-02-09
    • 2016-04-01
    • 1970-01-01
    • 2013-08-22
    • 2021-12-07
    相关资源
    最近更新 更多