简体   繁体   English

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

[英]Passing a class object as input parameter to a RESTful WCF service with POST request

I have created a RESTful WCF service and trying to pass a class as an parameter to a POST request using Fiddler but facing errors like: "HTTP/1.1 400 Bad Request" 我创建了一个RESTful WCF服务,并尝试使用Fiddler将类作为参数传递给POST请求,但遇到类似“ HTTP / 1.1 400 Bad Request”的错误

The Interface - IXmlService.cs 接口-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>

The Implementation - XmlService.cs 实现-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>

The Data Model - Order.cs 数据模型-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 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>

I tried different approaches by converting binding to 'webHttpBinding' in Web.Config. 我尝试通过将绑定转换为Web.Config中的“ webHttpBinding”来尝试其他方法。 Also, I tried adding ' BodyStyle = WebMessageBodyStyle.Wrapped' into the WebInvoke attribute but still not able to hit the service using fiddler. 另外,我尝试将'BodyStyle = WebMessageBodyStyle.Wrapped'添加到WebInvoke属性中,但仍然无法使用提琴手来访问该服务。

Fiddler Request: 提琴手要求:

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

Well, after wasting three days I finally figured out the error which is "Content Type" : I was using " Content-Type: text/xml " for JSON data which has to be " Content-Type: text/json ". 好吧,浪费了三天后,我终于发现了“ Content Type”错误:我对JSON数据使用“ Content-Type:text / xml ”,而JSON数据必须是“ Content-Type:text / json ”。


Guess i need to clean my spectacles on daily basis from now on :) 猜猜我从现在开始每天都要清洗眼镜:)

Use OrderId instead of Id an pass it a Guid instead of an int . 使用OrderId代替Id传递给Guid而不是int If that doesn't help, make CreatedOn temporarily a nullable DateTime and remove it from the POSTs body, just in case it's a date-format-thing. 如果那没有帮助, CreatedOn暂时将CreatedOn为可为空的DateTime并将其从POST主体中删除,以防万一它是一种日期格式的东西。 If you can't change CreatedOn pass a 'non-critical' value like "1/1/2013..." (day and month <= 12). 如果您不能更改CreatedOn传递一个“非关键”值,例如“ 1/1/2013 ...”(日期和月份<= 12)。

Hope this helps. 希望这可以帮助。

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

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