2011-08-29 138 views
5

送我瞭解一些這方面的文章,我發現,才達到該WCF得到POST請求的數據,我們添加通過WCF服務消費形式的數據通過郵局

[ServiceContract] 
public interface IService1 { 
    [OperationContract] 
    [WebInvoke(
     Method = "POST", 
     BodyStyle = WebMessageBodyStyle.Bare, 
     UriTemplate = "/GetData")] 
    void GetData(Stream data); 
} 

,並在實施

public string GetData(Stream input) 
{ 
    long incomingLength = WebOperationContext.Current.IncomingRequest.ContentLength; 
    string[] result = new string[incomingLength]; 
    int cnter = 0; 
    int arrayVal = -1; 
    do 
    { 
     if (arrayVal != -1) result[cnter++] = Convert.ToChar(arrayVal).ToString(); 
     arrayVal = input.ReadByte(); 
    } while (arrayVal != -1); 

    return incomingLength.ToString(); 
} 

我的問題是我應該怎麼做,在提交表單請求的行動將發送到我的服務和消費?

在Stream參數中,我是否可以通過Request [「FirstName」]從表單中獲取發佈信息?

回答

10

您的代碼沒有正確解碼請求正文 - 您正在創建一個數值爲string的值,每個值都包含一個字符。得到請求體後,你需要解析查詢字符串(使用HttpUtility是一個簡單的方法)。下面的代碼顯示瞭如何正確獲取主體和其中一個字段。

public class StackOverflow_7228102 
{ 
    [ServiceContract] 
    public interface ITest 
    { 
     [OperationContract] 
     [WebInvoke(
      Method = "POST", 
      BodyStyle = WebMessageBodyStyle.Bare, 
      UriTemplate = "/GetData")] 
     string GetData(Stream data); 
    } 
    public class Service : ITest 
    { 
     public string GetData(Stream input) 
     { 
      string body = new StreamReader(input).ReadToEnd(); 
      NameValueCollection nvc = HttpUtility.ParseQueryString(body); 
      return nvc["FirstName"]; 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     WebClient c = new WebClient(); 
     c.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; 
     Console.WriteLine(c.UploadString(baseAddress + "/GetData", "FirstName=John&LastName=Doe&Age=33")); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
+0

這是很好的解決方案Tnx;)但是在Test方法中,您調用服務併發送給它發送請求。在以

形式提交之後調用服務方法是可能的(也是巧妙的做法)?如果我這樣做,它會起作用嗎? :) – netmajor

+0

是的,它應該工作(測試方法模擬HTML表單發送的內容)。問題是,當你默認做一個表單提交時,你應該創建一個HTML頁面來發送它(而不是一個簡單的字符串),否則瀏覽器將只顯示你返回的字符串。另一個選擇是在submit表單中使用一些ajax調用,然後您可以將結果作爲XML(或JSON)返回並以內聯方式更新頁面。 – carlosfigueira