繁体   English   中英

400错误请求将xml有效负载发送到WCF REST服务

[英]400 bad request sending xml payload to WCF REST service

我知道有一些帖子询问400错误,我相信我已经阅读了所有这些错误,但我认为我面临的问题是不同的。

这是我的WCF服务合同

[WebInvoke(UriTemplate = "/cust_key/{key}/prod_id/{id}", 
           Method = "POST",
           BodyStyle = WebMessageBodyStyle.Bare, 
           RequestFormat = WebMessageFormat.Xml, 
           ResponseFormat = WebMessageFormat.Xml)]
Stream GetData(string key, string id, string data);

这是我用来将请求发送到我的休息svc的代码

request.RequestUri = 
     new Uri("http://localhost:3138/v1/cust_key/company1/prod_id/testProductID");
request.ContentType = "application/xml";
request.HttpMethod = "POST";

string xml = 
         @"<Product><name>dell 400</name><price>400 dollars</price></Product>";

byte[] message = Encoding.ASCII.GetBytes(xml);
string data = Convert.ToBase64String(message);
response = request.MakeWebRequest(null, data);

这给了我400个错误请求错误。 我试图将xml字符串更改为以下两个,它们也会产生400错误

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
       <![CDATA[<Product><name>dell 400</name><price>400 dollars</price></Product>]]>
</string>

要么

<![CDATA[<Product><name>dell 400</name><price>400 dollars</price></Product>]]>

如果有效负载xml是空字符串,那么一切都很好,返回200。 任何人都可以帮我一把吗?

编辑:我的web.config部分。 它从WCF REST服务模板40(CS)开箱即用

<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  <standardEndpoints>
  <webHttpEndpoint>
    <!-- 
        Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
        via the attributes on the <standardEndpoint> element below
    -->
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
  </webHttpEndpoint>
</standardEndpoints>

你的第二个使用<string>元素的例子应该可行。 如果您知道要接收的XML架构,则可以执行以下操作:

[WebInvoke(UriTemplate = "/cust_key/{key}/prod_id/{id}", 
       Method = "POST",
       BodyStyle = WebMessageBodyStyle.Bare, 
       RequestFormat = WebMessageFormat.Xml, 
       ResponseFormat = WebMessageFormat.Xml)]  
//Almost exacely the same except String is now Product in the method Parameters
Stream GetData(string key, string id, Product data);

[DataContract(Namespace = "")]
public class Prodect
{
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public string price { get; set; }
}

然后使用您帖子中的客户端代码,它应该可以正常工作。 另一方面,如果您希望Web服务动态接受不是明确定义的数据协定的不同XML,则可以使用XElement,如下所示:

[WebInvoke(UriTemplate = "/cust_key/{key}/prod_id/{id}", 
       Method = "POST",
       BodyStyle = WebMessageBodyStyle.Bare, 
       RequestFormat = WebMessageFormat.Xml, 
       ResponseFormat = WebMessageFormat.Xml)]  
//Almost exacely the same except String is now XElement
Stream GetData(string key, string id, XElement data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM