永久重定向传统路由ASP.Net MVC中的静态文件

时间:2011-01-12 02:43:39

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

我们旧的ASP.net网站将静态图像存储在名为 / images 的根目录下的子目录中。

我们的新ASP.net MVC网站将这些图片存储在 / Content / Images

的新布局中

我已经更改了网站中的所有页面以应对新的文件夹结构,但我想将旧的静态图像设置为永久重定向到新位置。

我们的网站是托管的,我无法控制IIS,那么解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

我在MVC 2网站上使用以下代码:

// The legacy route class that exposes a RedirectActionName
public class LegacyRoute : Route
{
    public LegacyRoute(string url, string redirectActionName, IRouteHandler routeHandler)
        : base(url, routeHandler)
    {
        RedirectActionName = redirectActionName;
        Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index"}); // is not actually called
    }

    public string RedirectActionName { get; set; }
}

// The legacy route handler, used for getting the HttpHandler for the request
public class LegacyRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        requestContext.HttpContext.Response.Write("success");
        return new LegacyHandler(requestContext);
    }
}

// The legacy HttpHandler that handles the request
public class LegacyHandler : MvcHandler
{
    public LegacyHandler(RequestContext requestContext) : base(requestContext)
    {
        requestContext.HttpContext.Response.Write("success");
        ProcessRequest(requestContext.HttpContext);
    }

    protected override void ProcessRequest(HttpContextBase httpContext)
    {
        string redirectActionName = ((LegacyRoute) RequestContext.RouteData.Route).RedirectActionName;
        var route = new Route(redirectActionName, ((LegacyRoute)RequestContext.RouteData.Route).Defaults, new MvcRouteHandler());

        // Copy all of the querystring parameters and put them within RouteContext.RouteData.Values
        var values = new Dictionary<string, object>();
        foreach (var s in RequestContext.RouteData.Values)
        {
            values.Add(s.Key, s.Value);
        }
        foreach (var s in httpContext.Request.QueryString.AllKeys)
        {
            values.Add(s, httpContext.Request.QueryString[s]);
        }
        var data = route.GetVirtualPath(RequestContext, new RouteValueDictionary(values));

        httpContext.Response.Status = "301 Moved Permanently";
        httpContext.Response.AppendHeader("Location", "/" + data.VirtualPath + "/");
        httpContext.Response.End();
    }
}

然后我只是将遗留路线添加到我的路线图中:

routes.Insert(13, new LegacyRoute("search", "search/{query}", new LegacyRouteHandler()));