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

Lag*_*una 5 .net c# xml rest wcf

我知道有一些帖子询问了 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);
Run Code Online (Sandbox Code Playgroud)

这是我用来将请求发送到我的休息 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);
Run Code Online (Sandbox Code Playgroud)

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

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
       <![CDATA[<Product><name>dell 400</name><price>400 dollars</price></Product>]]>
</string>
Run Code Online (Sandbox Code Playgroud)

或者

<![CDATA[<Product><name>dell 400</name><price>400 dollars</price></Product>]]>
Run Code Online (Sandbox Code Playgroud)

如果有效负载 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>
Run Code Online (Sandbox Code Playgroud)

Dan*_*ses 4

使用该元素的第二个示例<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; }
}
Run Code Online (Sandbox Code Playgroud)

然后使用您帖子中的客户端代码,它应该可以正常工作。另一方面,如果您希望 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);
Run Code Online (Sandbox Code Playgroud)