如何使用破折号使MVC路由处理URL

时间:2015-04-11 20:31:01

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

我在MVC中定义了如下路由:

routes.MapRoute(
   name: "ContentNavigation",
   url: "{viewType}/{category}-{subCategory}",
   defaults: new { controller = "Home", action = "GetMenuAndContent", viewType = String.Empty, category = String.Empty, subCategory = String.Empty });

如果我导航到http://example.com/something/category-and-this-is-a-subcategory

它将变量填充为:

viewType: "something"
category: "category-and-this-is-a"
subCategory: "subcategory".

我想要的是第一个短划线前的单词始终进入 category ,剩下的进入子类别。所以它会产生:

viewType: "something"
category: "category"
subCategory: "and-this-is-a-subcategory"

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:6)

一种可能性是编写自定义路由来处理路径段的正确解析:

public class MyRoute : Route
{
    public MyRoute()
        : base(
            "{viewType}/{*catchAll}",
            new RouteValueDictionary(new 
            {
                controller = "Home",
                action = "GetMenuAndContent",
            }),
            new MvcRouteHandler()
        )
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }

        var catchAll = rd.Values["catchAll"] as string;
        if (!string.IsNullOrEmpty(catchAll))
        {
            var parts = catchAll.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length > 1)
            {
                rd.Values["category"] = parts[0];
                rd.Values["subCategory"] = parts[1];
                return rd;
            }
        }

        return null;
    }
}

你会这样注册:

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

    routes.Add("ContentNavigation", new MyRoute());

    ...
}

现在假设客户端请求/something/category-and-this-is-a-subcategory,然后将调用以下控制器操作:

public class HomeController : Controller
{
    public ActionResult GetMenuAndContent(string viewType, string category, string subCategory)
    {
        // viewType = "something"
        // category = "category"
        // subCategory = "and-this-is-a-subcategory"

        ...
    }
}