How to make MVC Routing handle url with dashes

后端 未结 1 1899
感情败类
感情败类 2021-01-20 05:08

I have a route defined as follows in MVC:

routes.MapRoute(
   name: \"ContentNavigation\",
   url: \"{viewType}/{category}-{subCategory}\",
   defaults: new          


        
相关标签:
1条回答
  • 2021-01-20 06:00

    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"
    
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题