代码改变世界

ASP.NET MVC 中如何处理 ASP.NET WebForm 或其他历史遗留的 URL

2012-05-21 18:54  音乐让我说  阅读(442)  评论(0编辑  收藏  举报

当一个网站从 ASP.NET WebForm 转为 ASP.NET MVC 后,那些 URL 怎么办呢?

比如,原来通过 ~/articles/may/zebra-danio-health-tips.html 能访问某一个页面,那现在转为 ASP.NET MVC 了怎么办呢?

直接贴代码了:

1. 新建一个类,继承 RouteBase 类。

namespace DearBruce.LegacyUrlsRoute.MvcUI.Extensions
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Routing;
    using System.Web.Mvc;

    public class LegacyUrlsRoute : RouteBase
    {
        //可以从数据库中读取出原来的地址
        private static IList<string> legacyUrls = new List<string>()
        {
            "~/articles/may/zebra-danio-health-tips.html",
            "~/articles/VelociraptorCalendar.pdf",
            "~/guides/tim.smith/BuildYourOwnPC_final.asp"
        }.ToElementLower();


        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            string url = httpContext.Request.AppRelativeCurrentExecutionFilePath.ToLower();
            if (legacyUrls.Contains(url))
            {
                RouteData rd = new RouteData(this, new MvcRouteHandler());
                rd.Values.Add("controller", "Home");
                rd.Values.Add("action", "Old");
                rd.Values.Add("url", url);
                return rd;
            }
            else
            {
                return null; // Not a legacy URL
            }
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            return null;
        }
    }
}

 

2. 新建一个 List 泛型类的扩展方法。

namespace DearBruce.LegacyUrlsRoute.MvcUI.Extensions
{
    using System;
    using System.Collections.Generic;

    public static class ListExtensions
    {
        /// <summary>
        /// 返回每个小写的元素
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static IList<string> ToElementLower(this IList<string> items)
        {
            if (items == null || items.Count == 0)
            {
                return items;
            }
            for (int i = 0; i < items.Count; i++)
            {
                items[i] = items[i].ToLower();
            }
            return items;
        }
    }
}

 

3. 在 Global.asax 配置路由

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.Add("LegacyUrls", new DearBruce.LegacyUrlsRoute.MvcUI.Extensions.LegacyUrlsRoute());

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

 

运行效果:

 

 

谢谢浏览!