首页 文章

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

提问于
浏览
0

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

界面 - 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命中该服务 .

小提琴请求:

<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 回答

  • 1

    好吧,在浪费了三天之后我终于找到了错误"Content Type":我正在使用“ Content-Type: text/xml " for JSON data which has to be " Content-Type: text/json ” .

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

  • 0

    使用 OrderId 而不是 Id 传递 Guid 而不是 int . 如果这没有帮助,请暂时使 CreatedOn 成为可以为空的 DateTime 并将其从POST正文中删除,以防万一's a date-format-thing. If you can'改变 CreatedOn 传递'non-critical'值(如日和月<= 12) .

    希望这可以帮助 .

相关问题