有一个自托管的 WCF REST 服务,需要向其发送 xml post 消息。 似乎这个问题被问过并回答了好几次,但在尝试了每种解决方案后,我仍然没有取得任何成功。
服务器:接口(interface)
[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 的请求在“请求正文”中没有任何内容,工作正常,并在 Service 类的 ProcessMessage 方法内触发断点,“请求正文”中数据的任何变体, 例如:测试 || <inputXml>测试 || inputXml="测试"|| <inputXml>test 等给出 HTTP/1.1 400 错误请求
将不胜感激任何帮助
最佳答案
一些事情:
- 由于您使用的是
WebServiceHost
,因此无需显式添加服务端点(在 Main.cs 文件中调用host.AddServiceEndpoint(...)
)。 - 该操作采用
字符串
参数;如果要以 XML 形式发送,则需要将字符串包装在适当的元素中。试试这个 body ,它应该可以工作:
正文:
<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"
关于wcf - 将 xml 数据发送到 WCF REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6823640/