在WCF中的HTTP POST中发送Xml

时间:2013-06-01 20:51:58

标签: wcf

我在.net 3.5中使用wcf服务使用http post request发送xml。

但问题是当我设置request.ContentType =“text / xml”时它抛出异常

远程服务器返回错误:(400)错误请求。

我已经阅读了很多文章,但找不到任何可能的解决方案..

为什么它不支持ContentType =“text / xml”?

这是我的代码

//服务合同

[OperationContract(Name = "PostSampleMethod")]
[WebInvoke(Method = "POST",UriTemplate = "PostSampleMethod/New")]
string PostSampleMethod(Stream data);

// .....

 public string PostSampleMethod(Stream data)
    {
        // convert Stream Data to StreamReader
        StreamReader reader = new StreamReader(data);
        // Read StreamReader data as string
        string xmlString = reader.ReadToEnd();
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);

        string returnValue = doc.InnerXml;
        // return the XMLString data
        return returnValue;
    }

// WEB CONFIG ...

      <?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>

    <services>
      <service name="DemoHttpPost.HttpPost" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="DemoHttpPost.IHttpPost" behaviorConfiguration="web" >

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="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/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

// ...

以下是调用服务的代码。

private void button1_Click(object sender, EventArgs e)
        {

            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/DemoHttpPost/HttpPost.svc/PostSampleMethod/New");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            StringBuilder messagereturn = new StringBuilder();
            messagereturn.Append("<?xml version='1.0'?><id>");
            messagereturn.Append("123456");
            messagereturn.Append("</id>");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(messagereturn.ToString());

            string postData =doc.InnerXml;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "text/xml";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.

            WebResponse response = request.GetResponse();
            // Display the status.
            HttpWebResponse webres= (HttpWebResponse)response;

            StreamReader reader = new StreamReader(webres.GetResponseStream());
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            richTextBox1.Text = responseFromServer;
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }

1 个答案:

答案 0 :(得分:0)

例如

的ServiceContract

    [WebInvoke(Method="POST")]
    [OperationContract]
    void Send(string data);

服务

    public void Send(string data)
    {
        Console.WriteLine(data);
    }

客户,其中&#34; WebService&#34;是端点名称和IService - 服务合同

    using (var factory = new WebChannelFactory<IService>("WebService"))
    {
        var channel = factory.CreateChannel();
        channel.Send(@"<system.web>5</system.web>");
    }