c# - How to intercept a Url to dynamically change the routing -
c# - How to intercept a Url to dynamically change the routing -
i looking like:
for categories controller categorycontroller
www.mysite.com/some-category www.mysite.com/some-category/sub-category www.mysite.com/some-category/sub-category/another //this go on ..
the problem that: www.mysite.com/some-product
needs point productcontroller
. map same controller.
so, how can intercept routing can check if parameter category or product , route accordingly.
i trying avoid having www.mysite.com/category/some-category
or www.mysite.com/product/some-product
sense perform improve on seo side. when can intercept routing, i'll forwards product / category based on rules @ slugs each etc.
you write custom route serve purpose:
public class categoriesroute: route { public categoriesroute() : base("{*categories}", new mvcroutehandler()) { } public override routedata getroutedata(httpcontextbase httpcontext) { var rd = base.getroutedata(httpcontext); if (rd == null) { homecoming null; } string categories = rd.values["categories"] string; if (string.isnullorempty(categories) || !categories.startswith("some-", stringcomparison.invariantcultureignorecase)) { // url doesn't start some- per our requirement => // have no match route homecoming null; } string[] parts = categories.split('/'); // each of parts go nail categoryservice determine whether // category slug or else , homecoming accordingly if (!arevalidcategories(parts)) { // arevalidcategories custom method indicated route contained // parts not categories => have no match route homecoming null; } // @ stage know parts of url valid categories => // have match route , can pass categories action rd.values["controller"] = "category"; rd.values["action"] = "index"; rd.values["categories"] = parts; homecoming rd; } }
that registered that:
public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.add("categoriesroute", new categoriesroute()); routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "home", action = "index", id = urlparameter.optional } ); }
and can have corresponding controller:
public class categorycontroller: controller { public actionresult index(string[] categories) { ... categories action argument contain list of provided categories in url } }
c# asp.net-mvc routing asp.net-mvc-5.2
Comments
Post a Comment