How to make MVC Routing handle url with dashes

走远了吗. 提交于 2019-12-01 20:54:10

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;
    }
}

that you will register like that:

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"

        ...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!