如何读取HttpRequest的主体发布到REST Web服务 - C#WCF

Ser*_*e P 4 c# rest wcf web-services salesforce

我有一个Apex类(SalesForce中的一个类),可以调用REST Web服务.

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

REST Web服务(C#,WCF)如下所示:

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

Test()方法进行原始操作.

我跑的时候

WebServiceCallout.sendNotification("a test message")
Run Code Online (Sandbox Code Playgroud)

POST到达Web服务但是如何读取在方法中设置的HttpRequest 主体中设置的内容? reqsendNotification()req.setBody(aStr);

也就是说,参数应该是什么string Test(string aStr);

我是否需要指定其他任何内容,例如我WebInvokeApp.config(例如binding)中的任何配置/属性?

car*_*ira 6

如果要读取传入请求的原始主体,则应将参数类型定义为a Stream,而不是string.下面的代码显示了实现场景的一种方法,以及http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data上的帖子.aspx有关于这种"原始"模式的更多信息.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的传入请求在技术上是不正确的 - 你说(通过Content-Type)你发送的是JSON,但是请求体(a test message)不是一个有效的JSON字符串(它应该用引号括起来 - "a test message"是一个改为JSON字符串).