PROBLEM: Special characters particularly $ and £ are causing inconsistent behaviour in Web Api - ASP.NET C#. After calling the API the result is sometimes -
RESULT: {"Message":"An error has occurred."}
- REQUEST FORMAT: url + Message;
- FULL API CALL: ".........//api/data?Message=Test%20For%20%245700.00%20at%20"
- MESSAGE: "Test For $5700.00 at "
What I've tried
- Using Uri.EscapeDataString(request); to call the API, but the result is still not always 100% successful (50% of times it passes, the remaining 50% of times it comes up with the error message above)
- Removing the $ or £ symbol, it passes every time
QUESTION: Is there a way to allow special characters to pass through the API (just as a string)? Is there any way to get just the plain string back, even when a special character is included? Here's some code below that gets the message -
public List<Results> Get(string Message) { //DO SOMETHING WITH THE MESSAGE AS A STRING & RETURN RESULTS } Also, here's how I'm calling the API -
//CALLING API STEPS string url = ".....//api/data?Message="; string message = "Test For $5700.00 at "; string completeURL = url + Uri.EscapeDataString(message); var client = new WebClient(); var content = client.DownloadString(completeURL); I've added some additional test results below -
TEST RESULT - PASS
string url = ".....//api/data?Message="; string message = "Test For $5700.00 at "; message = message.Replace("$", "%24");//Adding this line before the URL-encoding fixes the problem string completeURL = url + Uri.EscapeDataString(message); var client = new WebClient(); var content = client.DownloadString(completeURL); //PASS - COMPLETE URL: ".....//api/data?Message=Test%20for%20%25245700.00%20at%20" //RESULT - API CALL SUCCESSFUL TEST RESULT - FAIL
string url = ".....//api/data?Message="; string message = "Test For $5700.00 at "; string completeURL = url + Uri.EscapeDataString(message); var client = new WebClient(); var content = client.DownloadString(completeURL); //FAIL - COMPLETE URL: ".....//api/data?Message=Test%20for%20%245700.00%20at%20" //RESULT - EXCEPTION -> "The remote server returned an error: (500) Internal Server Error."
Uri.EscapeDataString(request), but that's not the same as message... this is why showing the actual code is much more useful.) Now, you say this sometimes causes problems - could you give more details about that? Is it literally inconsistent between calls to the same URI, or does it always fail or always succeed for any given message?(500) Internal Server Errorusually means something went wrong in your code, not in Web API itself. Does yourGetmethod get invoked? What is the value of the Message parameter at that point? I would guess your "DO SOMETHING WITH THE MESSAGE..." code is where the problem lies.