发送xml数据到WCF REST服务

问题描述:

有一个自我托管的WCF REST服务,需要发送一个xml邮件消息给它。似乎这个问题似乎被问及几次回答,但在尝试了每个解决方案后,我仍然没有取得任何成功。发送xml数据到WCF REST服务

服务器:接口

[ServiceContract] 
public interface ISDMobileService 
{ 
    [OperationContract] 
    [WebInvoke(Method = "POST", BodyStyle=WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml)] 
    int ProcessMessage(string inputXml); 
} 

服务器:类

public class Service : ISDMobileService 
{ 
    public int ProcessMessage(string inputXml) 
    { 
     Console.WriteLine("ProcessMessage : " + inputXml); 
     return 0; 
    } 
} 

服务器:接待来自小提琴手

class Program 
{ 
    static void Main(string[] args) 
    { 
     WebServiceHost   host = new WebServiceHost(typeof(Service), new Uri("http://172.16.3.4:7310")); 
     WebHttpBinding   webbind = new WebHttpBinding(WebHttpSecurityMode.None); 

     ServiceEndpoint   ep  = host.AddServiceEndpoint(typeof(ISDMobileService), webbind, ""); 
     ServiceDebugBehavior stp  = host.Description.Behaviors.Find<ServiceDebugBehavior>(); 
     stp.HttpsHelpPageEnabled = false; 

     host.Open(); 
     Console.WriteLine("Service is up and running. Press 'Enter' to quit >>>"); 
     Console.ReadLine(); 

     host.Close(); 
    } 
} 

fiddler request

请求,而不在T什么他的“Request Body”工作得很好,并在Service类的ProcessMessage方法中触发断点,“请求正文”中的任何数据变体 例如:test || <inputXml> test </inputXml > || inputXml =“test”|| <?xml version =“1.0”encoding =“UTF-8”? > <inputXml>测试</inputXml >等给出了HTTP/1.1 400错误的请求

会明白这个

任何帮助,有几件事情:

  • 由于您使用WebServiceHost,你不需要明确添加服务端点(在您的Main中调用host.AddServiceEndpoint(...)
  • 该操作需要string参数;如果您想发送它n XML,你需要将字符串包装在适当的元素中。试试这个机构,它应该工作:

身体:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">This is a string encoded in XML</string> 

你也可以把它在不同的格式,如JSON。这个请求也应该可以工作

POST http://.../ProcessMessage 
Host: ... 
Content-Type: application/json 
Content-Length: <the actual length> 

"This is a string encoded in JSON" 
+0

完美的工作,非常感谢 – Maxim