How do I handle special characters in strings in a web service?
To show this fundamental problem in .NET and the reason behind this question, I wrote a simple test web service in one way (EditString) and with a console application that calls it.
They are standard webservices / consoles applications created with File / New Project etc., so I won't list all the code - just these methods:
Web Method:
[WebMethod]
public string EditString(string s, bool useSpecial)
{
return s + (useSpecial ? ((char)19).ToString() : "");
}
[You can see that it just returns the string s if useSpecial is false. If useSpecial is true, it returns s + char 19.]
Console application:
TestService.Service1 service = new SCTestConsumer.TestService.Service1();
string response1 = service.EditString("hello", false);
Console.WriteLine(response1);
string response2 = service.EditString("hello", true); // fails!
Console.WriteLine(response2);
[The second answer fails because the method returns hello + special character (ascii code 19 for argument sake).]
Error:
-
There is an error in the XML document (1, 287)
-
Inner exception: "'', hex 0x13, is an invalid character. Line 1, position 287 ..
A few notes:
-
The WORKS FINE web method itself looks directly at the ASMX file (for example
http://localhost:2065/service1.asmx
) and runs that method through this (with the same parameters as in the console application) - i.e. displays XML with the string hello + char 19. -
Checking the serialized XML in other ways shows that the special character is being encoded properly (it seems that SERVER SIDE is OK, which is GOOD)
-
So it seems that the CLIENT SIDE issue has a problem - that is, the .NET proxy class code does not handle special characters
-
This is part of a larger project in which objects are passed inside and outside of web methods that contain string attributes - that's what it takes to work properly. that is, we are de-serializing the classes.
Any suggestions for a workaround and how to implement it?
Or am I completely missing something really obvious !!?
PS. I was not very lucky to have it using CDATA tags (does .NET support them out of the box?).
I am thinking of some options that might help you. You can route using html objects instead of char (19). or as you said you can use CDATA.
To come up with a clean solution, you might not want to embed it all in CDATA. I'm not sure why you think this might not be supported in .NET. Are you saying this in the context of serialization?
a source to share