2

I have a C# WebApi 4 project where I am trying to have a string parameter with the character '/' in it. For example, I am passing a path in the parameter:

http://localhost/api/MyController/mypath/testing

I want the id parameter in Get method in MyController to be populated with "mypath/testing". However, it looks like the route things this should be two parameters and can't find where to go so it is returning in error.

I think I need to change the default route. Currently in the WebApiConfig class it is set to:

config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}/{id}",
     defaults: new { id = RouteParameter.Optional }
);

But I am not sure what type of pattern to use for this. Does anyone have any suggestions?

EDIT: If I change my URL to http://localhost/api/MyController?id=mypath/testing and modify the route to be:

config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}?{id}",
     defaults: new { id = RouteParameter.Optional }
);

Then the parameter does go though. However, I have a requirement to not change the URL pattern, and to not change the URL encoding.

lehn0058
  • 19,977
  • 15
  • 69
  • 109
  • 1
    encode it before passing it in? Don't use the `/` as a separator since that already has a use in the URL? The RFC tells you what's valid to be in a URL http://www.ietf.org/rfc/rfc3986.txt. Oh, and in case you get caught on this issue (for example, if you log someone in and use a `returnUrl` to go back to your current link in the example), double encoded URLs are fun in .NET: http://stackoverflow.com/questions/7251285/iis-treats-double-encoded-forward-slashes-in-urls-differently-on-the-first-reque – George Stocker Mar 05 '15 at 17:18
  • 1
    Only way I can think of is, `ControllerName/{*id}`. It has its limitations though. – Mat J Mar 05 '15 at 17:34
  • @Mathew, that works perfectly! If you add an answer, I will mark it as correct. Also, I am curious - what are some of the limitations you mentioned? – lehn0058 Mar 05 '15 at 17:42

1 Answers1

1

The '/' is reserve in the url, if you want to use it as parameter you should encode it. You need to encode it like this: %2F.

You can check all symbols which need encoding in this link

mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • http://localhost/api/MyController/mypath/testing is a valid path without encoding - for instance, if I have a different server with folders instead of using MVC. This is really more of a parsing issue with MVC, where it is parsing on '/' and expecting them to always be a route value instead of a string value. – lehn0058 Mar 05 '15 at 17:25