如何动态映射路由?

时间:2015-03-10 15:32:44

标签: asp.net webforms url-routing asp.net-mvc-routing

使用网站,我使用的是较新版本的ASP.NET中提供的内置路由工具,但它们目前不是动态的,它们被硬编码到global.asax文件的代码库中。

不确定这是否可行但是,有没有办法可以动态生成这些路线?

1 个答案:

答案 0 :(得分:0)

您可以继承RouteBase,以便根据动态数据集制作路线。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.Mvc;

public class ProductRoute : RouteBase
{

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RouteData result = null;

        string virutalPath = httpContext.Request.Url.AbsolutePath.Substring(1).ToLowerInvariant();

        // Call the database here to retrieve the productId based off of the virtualPath
        var productId = Product.GetProductIdFromVirtualPath(virutalPath);
        if (productId != Guid.Empty)
        {
            result = new RouteData(this, new MvcRouteHandler());
            result.Values["controller"] = "Product";
            result.Values["action"] = "Details";
            result.Values["id"] = productId;
        }

        return result;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        VirtualPathData result = null;
        string controller = Convert.ToString(values["controller"]);
        string action = Convert.ToString(values["action"]);

        if (controller == "Product")
        {
            string path = string.Empty;
            if (action == "Details")
            {
                Guid productId = (Guid)values["id"];

                // Call the database here to get the Virtual Path
                var virtualPath = Product.GetVirtualPathFromProductId(productId);
            }

            if (!String.IsNullOrEmpty(virtualPath))
            {
                result = new VirtualPathData(this, virtualPath);
            }
        }


        return result;
    }

}