如何使MVC路由处理URL以破折号 [英] How to make MVC Routing handle url with dashes

查看:128
本文介绍了如何使MVC路由处理URL以破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC定义为一个路线如下:

I have a route defined as follows in 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".

我要的是单词的第一个破折号总是进入的类别的面前,剩下的到的子类的。所以它会产生:

What I want is for the word before the first dash to always go into category, and the remaining into subcategory. So it would produce:

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

我怎样才能做到这一点?

How can I achieve this?

推荐答案

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

One possibility is to write a custom route to handle the proper parsing of the route segments:

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());

    ...
}

现在假设客户端请求 /事/类别和 - 这 - 是 - 一 - 子类别,那么下面的控制动作将被调用:

Now assuming that the client requests /something/category-and-this-is-a-subcategory, then the following controller action will be invoked:

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

        ...
    }
}

这篇关于如何使MVC路由处理URL以破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆