lehn0058
lehn0058

Reputation: 20257

How do you handle routing in ASP.Net WebApi routing with a '/' in your string parameter

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.

Upvotes: 2

Views: 906

Answers (1)

mybirthname
mybirthname

Reputation: 18127

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

Upvotes: 1

Related Questions