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

走远了吗. 提交于 2019-12-11 01:55:22

问题


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.


回答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



来源:https://stackoverflow.com/questions/28883767/how-do-you-handle-routing-in-asp-net-webapi-routing-with-a-in-your-string-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!