[英]WCF Rest do not accept xml declaration in request
我正在开发 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 Bad Request”。 WebException 的 InnerException 表示“协议错误”。
我用于发送的测试应用程序如下所示:
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;
}
谷歌搜索好几天了,请给我一个提示!
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 字符串是否与您在请求中提供的内容相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.