ASP.NET MVC中的动态内部重定向

时间:2014-01-10 13:19:43

标签: asp.net-mvc asp.net-mvc-routing asp.net-mvc-5

我搜索了很多,但没有找到任何解决方案。所以这是我的情况:

我有数据库模型UrlRedirect

public class UrlRedirect : AuditInfo
{
    [Key]
    public int Id { get; set; }

    public string OldUrl { get; set; }

    public string NewUrl { get; set; }
}

您可能认为我正在尝试保存OldUrlNewUrl之间的网址映射。

我想在内部将请求的OldUrl路径更改为NewUrl,然后运行所有已定义的路由,因为如果用户直接打开NewUrl,它们将会运行。

重定向应该是服务器端URL重写,用户应该在浏览器中看到旧URL

3 个答案:

答案 0 :(得分:3)

Global.asax中,您有一些在Web应用程序上下文中执行的事件。 (示例:Start_ApplicationEnd_Application等)。

在您的情况下,您可以使用BeginRequest事件,其中每个请求都会执行到您的Web应用程序。在这种情况下,您可以检查URL并尝试使用默认的htpp协议重定向它,例如301 Moved Permanently状态代码。例如,在Global.asax文件中,添加以下代码:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    // get the current url
    string currentUrl = HttpContext.Current.Request.Url.ToString().ToLower(); 

    // here, you could create a method to get the UrlRedirect object by the OldUrl.
    var urlRedirect = GetUrlRedirect(currentUrl);

    // check if the urlRedirect object was found in dataBase or any where you save it
    if (urlRedirect != null)
    {
        // redirect to new URL.
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", urlRedirect.NewUrl);
        Response.End();
    }
}

在示例中,GetUrlRedirect(string)方法应在数据库,xml文件,缓存或保存UrlRedirect对象的任何位置检查它。

要了解有关asp.net核心应用程序生命周期如何工作的更多信息,请阅读this article

答案 1 :(得分:1)

如果您真的想在服务器中重定向,可以使用以下方法之一:

  • HttpServerUtility.TransferRequest
  • HttpServerUtility.Transfer
  • HttpServerUtility.Execute
  • HttpContext.RewritePath

您可以阅读有关这些选项的更多信息,其中提出类似的问题here

考虑您选择对请求服务性能的影响。恕我直言,你应该尽量利用路由的MVC基础设施,或者只是回到简单的重定向(甚至永久性的速度),如[user:316799]在业务层或数据库中计算新网址时写的那样。

答案 2 :(得分:1)

这是我的最终解决方案,就像一个魅力。感谢@WeTTTT的想法。

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        // ...
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        this.ApplyCustomUrlRedirects(new UowData(), HttpContext.Current);
    }

    private void ApplyCustomUrlRedirects(IUowData data, HttpContext context)
    {
        var currentUrl = context.Request.Path;
        var url = data.UrlRedirects.All().FirstOrDefault(x => x.OldUrl == currentUrl);
        if (url != null)
        {
            context.RewritePath(url.NewUrl);
        }
    }
}