Serge P
Serge P

Reputation: 1611

How to read body of HttpRequest POSTed to a REST web service - C# WCF

I have an Apex Class (a class in SalesForce) that calls out to a REST web service.

public class WebServiceCallout 
{
    @future (callout=true)
    public static void sendNotification(String aStr) 
    {
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();

        req.setEndpoint('http://xx.xxx.xxx.xx:41000/TestService/web/test');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(aStr); // I want to read this in the web service

        try 
        {
            res = http.send(req);
        } 
        catch(System.CalloutException e) 
        {
            System.debug('Callout error: '+ e);
            System.debug(res.toString());
        }
    }
}

The REST web service (C#, WCF) looks like so:

public interface ITestService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
     ResponseFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Bare,
     UriTemplate = "/test")]
    string Test(string aStr);
}

The Test() method does primitive operations.

When I run

WebServiceCallout.sendNotification("a test message")

the POST gets to the web service but how can I read what was set in the body of the HttpRequest req that was set back in the sendNotification() method - req.setBody(aStr);?

That is, what should the parameter of string Test(string aStr); be?

Do I need to specify anything else such as any configs/attributes in my WebInvoke or the App.config (e.g. the binding)?

Upvotes: 4

Views: 10875

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87308

If you want to read the raw body of the incoming request, you should define the type of the parameter as a Stream, not string. The code below shows one way to implement your scenario, and the post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx has more information on this "raw" mode.

public class StackOverflow_25377059
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
         ResponseFormat = WebMessageFormat.Json,
         BodyStyle = WebMessageBodyStyle.Bare,
         UriTemplate = "/test")]
        string Test(Stream body);
    }

    public class Service : ITestService
    {
        public string Test(Stream body)
        {
            return new StreamReader(body).ReadToEnd();
        }
    }

    class RawMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            return WebContentFormat.Raw;
        }
    }

    public static void Test()
    {
        var baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        var host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        var binding = new WebHttpBinding { ContentTypeMapper = new RawMapper() };
        host.AddServiceEndpoint(typeof(ITestService), binding, "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        var req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "/test");
        req.Method = "POST";
        req.ContentType = "application/json";
        var reqStream = req.GetRequestStream();
        var body = "a test message";
        var bodyBytes = new UTF8Encoding(false).GetBytes(body);
        reqStream.Write(bodyBytes, 0, bodyBytes.Length);
        reqStream.Close();
        var resp = (HttpWebResponse)req.GetResponse();
        Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        foreach (var header in resp.Headers.AllKeys)
        {
            Console.WriteLine("{0}: {1}", header, resp.Headers[header]);
        }

        Console.WriteLine();
        Console.WriteLine(new StreamReader(resp.GetResponseStream()).ReadToEnd());
        Console.WriteLine();
    }
}

By the way, your incoming request is not technically correct - you say (via Content-Type) that you're sending JSON, but the request body (a test message) is not a valid JSON string (it should be wrapped in quotes - "a test message" to be a JSON string instead).

Upvotes: 6

Related Questions