使用POST请求将类对象作为输入参数传递给RESTful WCF服务

时间:2016-11-18 04:50:02

标签: c# rest wcf asp.net-web-api fiddler

我创建了一个RESTful WCF服务并尝试使用Fiddler将类作为参数传递给POST请求,但是遇到如下错误: “HTTP / 1.1 400错误请求”

界面 - IXmlService.cs

<code>

     [ServiceContract()]
        public interface IXmlService
        {
            [OperationContract(Name = "Read")]
            [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Read", BodyStyle = WebMessageBodyStyle.Wrapped)]
            bool ReadData(Order data);

            [OperationContract(Name = "Generate")]
            [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Generate/")]
            bool GenerateXml();
        }
</code>

实施 - XmlService.cs

<code>

    public class XmlService : IXmlService
        {
            public bool ReadData(Order data)
            {
                bool result = false;
                var path = "@C:\\order.xml";
                XmlSerializer serializer;
                TextWriter writer;

                try
                {
                    if (data != null)
                    {
                        //serializer = new XmlSerializer(typeof(Order), new XmlRootAttribute("HEADER"));
                        serializer = new XmlSerializer(typeof(Order));  //No need to provide XmlRootAttribute as I have defined it on Order Model.
                        writer = new StreamWriter(path);
                        serializer.Serialize(writer, data);
                        result = true;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return result;
            }

            public bool GenerateXml()
            {
                throw new NotImplementedException();
            }
        }

</code>

数据模型 - Order.cs

<code>

     [XmlRootAttribute("OrderDetails", Namespace = "http://www.ProofOfConcept.com", IsNullable = false)]
        [DataContract]
        public class Order
        {
            // The XmlArrayAttribute changes the XML element name
            // from the default of "OrderedItems" to "Items".
            [XmlElement("OrderId")]
            [Key]
            [DataMember]
            public int OrderId { get; set; }

            [DataMember]
            public string Owner { get; set; }

            // Setting the IsNullable property to false instructs the 
            // XmlSerializer that the XML attribute will not appear if 
            // the City field is set to a null reference.
            [XmlElementAttribute(IsNullable = false)]
            [DataMember]
            public string Info { get; set; }

            [DataMember]
            public string Recipient { get; set; }

            //[DataMember]
            //public DateTime CreatedOn { get; set; }
        }

</code>

的Web.config

<code>

      <system.serviceModel>
        <services>
          <service name="WCF_XML_Service.XmlService" behaviorConfiguration="ServiceBehavior">
            <!-- Service Endpoints -->
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:16999"/>
              </baseAddresses>
            </host>

            <endpoint address="/xml/" binding="webHttpBinding" contract="WCF_XML_Service.IXmlService" behaviorConfiguration="Web"/>
          </service>
        </services>

        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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 helpEnabled="true"/>
            </behavior>
          </endpointBehaviors>
        </behaviors>

</code>

我通过在Web.Config中将绑定转换为'webHttpBinding'来尝试不同的方法。此外,我尝试将“BodyStyle = WebMessageBodyStyle.Wrapped”添加到WebInvoke属性中,但仍然无法使用fiddler命中该服务。

Fiddler请求:

 <code>
Url - http://localhost:16999/XmlService.svc/xml/Read
Method - POST
Request Header:
User-Agent: Fiddler
Host: localhost:16999
Content-Type: text/xml
Content-Length: 155

Request Body:
    {
    "OrderId": "1", 
    "Owner": "Sam Shipping",
    "Info": "First delivery shipment",
    "Recipient": "Singapore Shipping Corporation"
    }
    </code>

2 个答案:

答案 0 :(得分:1)

好吧,在浪费了三天之后我终于找到了错误,即“内容类型”: 我使用“ Content-Type:text / xml ”作为JSON数据,必须是“ Content-Type:text / json ”。

左边猜猜我现在需要每天清洁我的眼镜:)

答案 1 :(得分:0)

使用OrderId而非Id传递Guid而不是int。如果这没有帮助,请暂时使CreatedOn成为可以为空的DateTime并将其从POST正文中删除,以防万一它是日期格式的东西。如果您无法更改CreatedOn通过“非关键”&#39;价值像&#34; 2013年1月1日...&#34; (日和月&lt; = 12)。

希望这有帮助。