我正在开发WCF REST服务,以接收来自第三方公司的输入。如果我发送一个简单的xml结构,它可以正常工作,但是如果请求中存在xml声明,则它会失败。不幸的是,我无法控制正在发送的内容,因此必须使用声明来完成此工作。
我的服务界面和实现如下:
[ServiceContract(Namespace = "")]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "report")]
ResponseData Report(testclass req);
}
public class Service : IService1
{
public string Report(testclass req)
{
return req.operatorStatusMessage;
}
}
这是我的测试班:
[DataContract(Namespace = "", Name = "testclass")]
public partial class testclass
{
[DataMember]
public ushort id { get; set; }
[DataMember]
public byte statusCode { get; set; }
[DataMember]
public string statusMessage { get; set; }
public testclass()
{ }
}
..这是我的Web.config
<system.serviceModel>
<services>
<service name="SMSRep.Service" behaviorConfiguration="serviceBehavior">
<endpoint address="" binding="webHttpBinding" contract="SMSRep.IService" behaviorConfiguration="webHttp" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" maxReceivedMessageSize="50000" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
我要发送的xml是
<?xml version = "1.0" encoding="UTF8" ?>
<testclass>
<id>6789</id>
<statusCode>200</statusCode>
<statusMessage>Some message</statusMessage>
</testclass>
正如我提到的,如果没有xml声明,它就可以正常工作, 如果包含,则会收到错误“ 400错误请求”。 WebException的InnerException表示“协议错误”。
我发送的testapp看起来像这样:
const string url = "http://localhost:4337/Service.svc/Report";
string txt = File.ReadAllText(xmlfile);
byte[] requestBytes = Encoding.UTF8.GetBytes(txt);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml;charset=utf-8";
req.Timeout = 10000;
req.ContentLength = requestBytes.Length;
using (Stream streamWriter = req.GetRequestStream())
{
streamWriter.Write(requestBytes, 0, requestBytes.Length);
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
txtReceive.Text = result;
}
已经使用谷歌搜索了好几天,请给我一个提示!
答案 0 :(得分:0)
xml 文件应该有架构实例。试试这样添加
<testclass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<id>6789</id>
<statusCode>200</statusCode>
<statusMessage>Some message</statusMessage>
</testclass>
注意:删除根xml节点。
如果这也失败了。尝试使用 DataContractSerializer 对 服务中的合同 进行数据合同序列化,然后检查 xml 字符串是否与您在请求中提供的内容相匹配。