简体   繁体   中英

How to route an url with an url in it in MVC

Basically I would like to take an url like:

http://example.com/community/www.foo.com/bar

...and give it to my http://example.com/community/ view with www.foo.com/bar in some variable that razor can access in the view.

How could this be done?

Note: I tried this:

routes.MapRoute(
    "Community",                                           
    "{controller}/{url}",                           
    new { controller = "Community", action = "Index", url = "" }
);

which worked with http://example.com/community/www.foo.com but not http://example.com/community/www.foo.com/bar (IIS tried to resolve the latter and gave a 404).

From MSDN :

Sometimes you have to handle URL requests that contain a variable number of URL segments. When you define a route, you can specify that if a URL has more segments than there are in the pattern, the extra segments are considered to be part of the last segment. To handle additional segments in this manner you mark the last parameter with an asterisk (*). This is referred to as a catch-all parameter. A route with a catch-all parameter will also match URLs that do not contain any values for the last parameter. The following example shows a route pattern that matches an unknown number of segments.

 query/{queryname}/{*queryvalues} 

In your case it will be:

routes.MapRoute(
    "Community",                                           
    "{controller}/{*url}",                           
    new { controller = "Community", action = "Index", url = "" }
);

Alternative and more robust approach is using some kind of encoding for the URL part - for example Base64URI encoding from RFC4648

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM