开发者

Asp.net MVC custom routing

开发者 https://www.devze.com 2023-01-08 02:52 出处:网络
I need to create a 开发者_如何学运维custom routing for this url: /par1/par2/par3/par99/11 The url must redirect to

I need to create a 开发者_如何学运维custom routing for this url:

/par1/par2/par3/par99/11

The url must redirect to

home/index/11

11 is the Id

I need only this parameter, the other parameter (par1/par2/...) are only for SEO purpose and could be any word.

par1, par2, etc.. are created dynamically , so the Url could be:

/par1/par2/11

or

/par1/par2/par3/111

or

/par1/3


you could just turn it around and go with

routes.MapRoute(
    "Route",
    "{id}/{*seostuff}",
    new {controller = "Home", action="Index", seo = UrlParameter.Optional});

that will allow you to map urls such as http://www.somesite.com/11/whatever/goes-here/will-be-whatever-you/want


Maybe you'll start with this and adjust to your needs:

routes.MapRoute(
    "Def0", // Route name
    "{controller}/{action}/{seo1}/{seo2}/{seo3}/{id}"
);

routes.MapRoute(
    "Def1", // Route name
    "{controller}/{action}/{seo1}/{seo2}/{id}"
);

routes.MapRoute(
    "Def2", // Route name
    "{controller}/{action}/{seo1}/{id}"
);

routes.MapRoute(
    "Def3", // Route name
    "{controller}/{action}/{id}"
);


Since your id is at the end, you would need to make 99 routes to handle all the stuff in between in order for the id route to the controller (easily).

I would stick the id to the left of the "SEO stuff" if possible, so it can be thrown away easier, exactly like @Morder described. The {*seostuff} parameter catches forward slashes ('/'), whereas thee {seo1}, {seo2} parameters do not.

look at the way stackoverflow does urls; after the id everything is thrown away.


I know this has already been accepted but I've written a route class that allows greedy segment to be anywhere in the URL definition.

In this case URL definition would be

{*seo}/{id}

Read all details about the custom route class and use it if you like:

Custom Asp.net MVC route class with catch-all segment anywhere in the URL

0

精彩评论

暂无评论...
验证码 换一张
取 消