【问题标题】:How to read body of HttpRequest POSTed to a REST web service - C# WCF如何读取发布到 REST Web 服务的 HttpRequest 正文 - C# WCF
【发布时间】:2014-08-19 06:37:16
【问题描述】:

我有一个调用 REST Web 服务的 Apex 类(SalesForce 中的一个类)。

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());
        }
    }
}

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

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

Test() 方法执行原始操作。

当我跑步时

WebServiceCallout.sendNotification("a test message")

POST 进入 Web 服务,但我如何才能读取 HttpRequest reqbody 中设置的内容,而 sendNotification()方法——req.setBody(aStr);?

string Test(string aStr);的参数应该是什么?

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

【问题讨论】:

    标签: c# web-services wcf rest salesforce


    【解决方案1】:

    如果要读取传入请求的原始正文,则应将参数的类型定义为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();
        }
    }
    

    顺便说一句,您的传入请求在技术上不正确 - 您说(通过 Content-Type)您正在发送 JSON,但请求正文 (a test message) 不是有效的 JSON 字符串(它应该被包装在引号中 - "a test message" 改为 JSON 字符串)。

    【讨论】:

    • 感谢您澄清测试消息不是有效的 JSON,我想知道为什么需要对字符串进行双引号!
    • 是的,你应该像这样传递 JSON 数据:var body = "msg:\"a test message\"";
    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 2014-10-13
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    相关资源
    最近更新 更多