简体   繁体   中英

how to handle parameter with space and slash in uri C# WEB API 2

I have an controller called Test Controller and the method name is Test The Test Method accepts one parameter. But when the parameter contains value having space slash the web api is giving error. I am using WEB API 2.

[Route("Test/{companyName}")]
[AcceptVerbs("GET", "POST")]
[System.Web.HHttpGet]

public HttpResponseMessage Test(string companyName)
{
}

the parameter value is BTL / Force Motor Ltd.

I have tried but nothing happened.

<uri>
  <schemeSettings>
    <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
  </schemeSettings>
</uri>

You need to URL Encode the values you are sending to your API, like this:

http://yourApiDomainName/api/yourControllerName/?companyName=BTL%20%2F%20Force%20Motor%20Ltd

[SPACE] when URL encoded beomes: %20

[Forward Slash] when URL encoded becomes: %2F

you dont need to http decode the values in your controller, as these values will be decoded by the framework as soon as they reach your controller. So you will see 'BTL%20%2F%20Force%20Motor%20Ltd' as 'BTL / Force Motor Ltd' inside your controller.

for full list of URL Encodings see this: http://www.w3schools.com/tags/ref_urlencode.asp

Your issue has nothing to do with WebAPI itself but how ASP.Net handles some specific Urls. This may also affect any dots (".") that get passed in to your API. Here's what worked for me:

Add this line to your web.config under system.web

<httpRuntime relaxedUrlToFileSystemMapping="true" />

Phil Haacked has a great article that goes into more detail.

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