【问题标题】:WCF WebInvoke POST message bodyWCF WebInvoke POST 消息正文
【发布时间】:2015-03-02 19:28:16
【问题描述】:
[OperationContract]
[WebInvoke(UriTemplate = "s={s}", Method = "POST")]
string EchoWithPost(string s);

我正在尝试使用WebRequest 使用此方法(WCF 服务):

WebRequest request1 = WebRequest.Create("http://MyIP/Host");
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
string postData1 = "s=TestString";

我不想在 url 中传递数据 (s=TestString),我想做的是在消息正文中传递数据。

【问题讨论】:

    标签: c# wcf post webinvoke


    【解决方案1】:

    首先你需要像这样改变你的服务合同:

    [OperationContract]
    [WebInvoke(UriTemplate = "EchoWithPost", Method = "POST")]
    string EchoWithPost(string s);
    

    请注意UriTemplate 如何不再期待 URL 中的任何变量值。

    从客户端调用这样的操作:

    // Set up request
    string postData = @"""Hello World!""";
    HttpWebRequest request = 
         (HttpWebRequest)WebRequest.Create("http://MyIP/Host/EchoWithPost");
    request.Method = "POST";
    request.ContentType = "text/json";
    byte[] dataBytes = new ASCIIEncoding().GetBytes(postData);
    request.ContentLength = dataBytes.Length;
    using (Stream requestStream = request.GetRequestStream())
    {
         requestStream.Write(dataBytes, 0, dataBytes.Length);
    }
    
    // Get and parse response
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string responseString = string.Empty;
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
         //responseData currently will be in XML format 
         //<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello World!</string>
         var responseData = responseStream.ReadToEnd();
         responseString = System.Xml.Linq.XDocument.Parse(responseData).Root.Value;
    }
    
    // display response - Hello World!
    Console.WriteLine(responseString);
    Console.ReadKey(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多