Search code examples
.netwcfwebhttpbindingoperationcontracturitemplate

Getting Gibberish instead of Hello World from a service with webHttpBinding


Here is a trivial example that is supposed to return "Hello World" string. However, a browser displays something like SGVsbG8gV29ybGQ=. Which is the right way to return plain text from an oldskul-style service?

please know that:

  1. I can't return a string: three Unicode characters will be automatically prepended and the legacy HTTP client won't be able to interoperate.

  2. I could return a Message, but still must keep parsing functionality to extract the data variable. Mixing Message and int types in the same method signature is not allowed AFAIK.

    [ServiceContract(SessionMode=SessionMode.NotAllowed)] 
    public interface IHello 
    {
      [WebGet(UriTemplate = "manager?data={data}")]
      [OperationContract]
      Byte[] DoIt(int data);
    }

    public class Hello : IHello { public Byte[] DoIt(int data) { return Encoding.ASCII.GetBytes("HelloWorld"); } }

UPDATE: It's not gibberish, but correctly encoded response. However, the format is not what I'd expect to receive. I've figured out (as gentlemen below suggest) that the ultimate control of the transport layer messaging format is gained with Message class. However, if I do use one - I loose the possibility of parsing the request (UriTemplate attribute). Hence, it would be great to know how to integrate the Message with UriRequest.

P.S. If the "clean" integration is not possible - than what's the most elegant workaround? Is there any code that is done behind the wire curtain that I can borrow and use in my implementation, please?


Solution

  • Googled for a proper way to integrate and found that people are stuck just as I am (please correct me if I am wrong on that). So far the following workaround works fine for me:

      public class Hello : IHello
      {
            [WebGet(UriTemplate = "manager")]
            [OperationContract]
            Message DoIt();
      }
    
      public class Hello : IHello
      {
            public Message DoIt()
            {
              var webContext = WebOperationContext.Current;
              var request = webContext.IncomingRequest;
              var queryParameters = request.UriTemplateMatch.QueryParameters;
              var data = queryParameters["data"];
    
              var result = new StringBuilder(@"
                  <?xml version='1.0'?>
                  ...
              ");
    
              var response = webContext.CreateTextResponse(result.ToString(), "application/xml", Encoding.ASCII);
    
              return response;
            }
      }
    

    If there is a better alternative - it would be perfect to know about it.