远程服务器返回错误“(400)Bad Request.ContentType =”text / xml;字符集= UTF-8"

时间:2013-06-17 17:05:00

标签: .net wcf rest post

我有一个简单的WCF POST,它将简单的XML发布到服务中。

这是服务合同。

[ServiceContract]
public interface ITest
{
    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "PostTest")]
   Stream PostTest(Stream testInfo);  
}

配置,没什么特别的。

<system.serviceModel>
<services>
  <service name="T.Test" behaviorConfiguration="ServiceBehaviour">
    <!-- Service Endpoints -->
    <!-- Unless fully qualified, address is relative to base address supplied above -->
    <endpoint address ="" binding="webHttpBinding" contract="T.ITest" behaviorConfiguration="web">
      <!-- 
          Upon deployment, the following identity element should be removed or replaced to reflect the 
          identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
          automatically.
      -->
    </endpoint>
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

          

只要我不提及内容类型,当我从简单的客户端测试时,一切都有效。

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
  

req.ContentType =&#34; text / xml;字符集= UTF-8&#34 ;;

var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.Load("../../PostData.xml");
string sXml = xmlDoc.InnerXml;
Console.Write(sXml + Environment.NewLine + Environment.NewLine);

req.ContentLength = sXml.Length;
var sw = new StreamWriter(req.GetRequestStream());
sw.Write(sXml);
sw.Close();

HttpWebResponse res = (HttpWebResponse)req.GetResponse();

经过一些研究后,我了解这是soap 1.1与soap 1.2之间的兼容性问题。但是如何在服务器端修复此问题?

2 个答案:

答案 0 :(得分:0)

我不认为这与SOAP版本问题有关,因为webHttpBinding是REST绑定,而不是SOAP绑定

在请求上设置ContentType标头告诉服务客户端必须使用请求的内容类型进行响应。您实际回应的内容类型是什么?如果不是text/xml; charset=utf-8,则可以解释错误。

根据文档,ContentType的默认回复webHttpBindingapplication/xmlapplication/octet-stream,用于流式回复。

如果您未在contentType上指定任何HttpWebRequest,fiddler会告诉我ContentType标头设置为text/html, application/xhtml+xml, */*

通配符表示任何响应类型都可以 - 包括服务器响应的application/octet-stream。如果您没有设置内容类型,这就是它的原因。

只要将客户端ContentType标头设置为text/xml,它就不再与服务响应的内容相匹配,从而导致错误。

如果您无法在客户端上设置请求ContentType,则必须在服务器上执行此操作。这篇文章给出了如何做到这一点的链接

WCF REST WebService content type is wrong

这会提供更多信息

http://msdn.microsoft.com/en-us/library/ee476510.aspx

答案 1 :(得分:0)