ASP.NET Web Service - how to handle special characters in strings?

Posted by Vlorg on Stack Overflow See other posts from Stack Overflow or by Vlorg
Published on 2009-05-17T17:36:10Z Indexed on 2010/05/29 21:22 UTC
Read the original article Hit count: 388

To show this fundamental issue in .NET and the reason for this question, I have written a simple test web service with one method (EditString), and a consumer console app that calls it.

They are both standard web service/console applications created via File/New Project, etc., so I won't list the whole code - just the methods in question:

Web method:

    [WebMethod]
    public string EditString(string s, bool useSpecial)
    {
        return s + (useSpecial ? ((char)19).ToString() : "");
    }

[You can see it simply returns the string s if useSpecial is false. If useSpecial is true, it returns s + char 19.]

Console app:

        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 response fails, because the method returns hello + a special character (ascii code 19 for argument's sake).]

The error is:

  • There is an error in XML document (1, 287)

  • Inner exception: "'', hexadecimal value 0x13, is an invalid character. Line 1, position 287."

A few points worth mentioning:

  • The web method itself WORKS FINE when browsing directly to the ASMX file (e.g. http://localhost:2065/service1.asmx), and running the 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 the special character is being encoded properly (the SERVER SIDE seems to be ok which is GOOD)

  • So it seems the CLIENT SIDE has the issue - i.e. the .NET generated proxy class code doesn't handle special characters

  • This is part of a bigger project where objects are passed in and out of the web methods - that contain string attributes - these are what need to work properly. i.e. we're de/serializing classes.

Any suggestions for a workaround and how to implement it?

Or have I completely missed something really obvious!!?

Thanks in advance...

PS. I've not had much luck with getting it to use CDATA tags (does .NET support these out of the box?).

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about web-services