Sunday, October 31, 2010

C# Web Service Plain Text Response

It took me far longer than I expected in order to figure out how to return plain text from a C# web service. I'm not sure why this took so long for me to figure out, but if it wasn't just me, then maybe this post can help other people out.

The Problem: When writing a web service endpoint in C#, if the return type is a String, the result will be an XML formatted string.

For example, the following web service:
  1. public String TestServiceA(Stream input)
  2. {
  3. return "Some kind of Text";
  4. }
returns the following string:
  1. <string>Some kind of Text</string>
It isn't that big a deal and the contained text can be easily parsed out, but it wasn't what I wanted and extra parsing code somehow seems wrong. I wanted the result to simply be the text I set.

The Solution: The return type needs to be a Stream.

So now the following web service:
  1. public Stream TestServiceB(Stream input)
  2. {
  3. MemoryStream ms = new MemoryStream();
  4. StreamWriter sw = new StreamWriter(ms);
  5. sw.Write("Some kind of Text");
  6. sw.Flush();
  7. ms.Position = 0;
  8. return ms;
  9. }
returns the expected result:
  1. Some kind of Text

No comments: