如何在ASP.Net WebApi路由中使用字符串参数中的"/"来处理路由 [英] How do you handle routing in ASP.Net WebApi routing with a '/' in your string parameter

查看:190
本文介绍了如何在ASP.Net WebApi路由中使用字符串参数中的"/"来处理路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#WebApi 4项目,我试图在其中包含一个带有字符'/'的字符串参数.例如,我在参数中传递路径:

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

我希望MyController的Get方法中的id参数填充"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.

我认为我需要更改默认路由.当前在WebApiConfig类中,它设置为:

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?

如果我将URL更改为 http://localhost/api/MyController?id = mypath/testing 并将路由修改为:

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 }
);

然后参数确实消失了.但是,我有一个要求,不要更改URL模式,也不要更改URL编码.

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

推荐答案

URL中保留'/',如果要将其用作参数,则应对其进行编码.您需要这样编码:%2F.

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.

您可以在此链接

这篇关于如何在ASP.Net WebApi路由中使用字符串参数中的"/"来处理路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆