2011-01-13 82 views
0

我有一個我在Silverlight中創建的Web客戶端。我試圖通過GET和POST請求和JSON將它與我的服務器上的Web服務進行通信。 GET請求正常工作,我能夠解析Silverlight端的JSON。但POST請求似乎不起作用。服務器讀取有POST請求,但POST數組爲空。JSON Silverlight發佈的數據未到達服務器

我試了兩段代碼來發送POST請求,但都導致相同的響應 - 一個空的數組。

第一Silverlight的代碼我嘗試是:

public MainPage() 
    { 
     InitializeComponent(); 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.dipzo.com/game/services.php")); 
     request.Method = "POST"; 
     request.ContentType = "application/json"; 
     request.BeginGetRequestStream(new AsyncCallback(OnGetRequestStreamCompleted), request); 
    } 

    private void OnGetRequestStreamCompleted(IAsyncResult ar) 
    { 
     HttpWebRequest request = (HttpWebRequest)ar.AsyncState; 
     using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(ar))) 
     { 
      writer.Write("name=david"); 
     } 
     request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request); 
    } 

    private void OnGetResponseCompleted(IAsyncResult ar) 
    { 
     //this.GetResponseCoimpleted.Visibility = Visibility.Visible; 

     // Complete the Flickr request and marshal to the UI thread 
     using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar)) 
     { 
      using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
      { 
       string results = reader.ReadToEnd(); 
      } 
     } 
    } 

我嘗試的第二件是:

private void WebClient_Click(object sender, RoutedEventArgs e) 
    { 
     Test t1 = new Test() { Name = "Civics", Marks = 100 }; 
     DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Test)); 
     MemoryStream mem = new MemoryStream(); 
     jsondata.WriteObject(mem, t1); 
     string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length); 
     WebClient cnt = new WebClient(); 
     cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted); 
     cnt.Headers["Content-type"] = "application/json"; 
     cnt.Encoding = Encoding.UTF8; 
     cnt.UploadStringAsync(new Uri("http://www.dipzo.com/game/services.php"), "POST", josnserdata); 
    } 

    void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
    { 
     var x = e; 
    } 

在服務器上的代碼來使用服務是在PHP和基本上是: var_dump($ _ POST)

這應該輸出任何進入後數組。我已經用一個簡單的PHP客戶端進行了測試,它可以工作。只是無法讓它在silverlight中工作。在Silverlight中,我只是繼續獲得一個空數組。

回答

1

,則應該更換內容類型應用程序/ x-WWW窗體-urlencoded,而不是應用程序/ JSON這不是一個已知類型呢。

0

不是我認爲任何人仍然關注他的老問題,但我敢打賭問題是它實際上到達了服務器,但是服務器將結果路由回SL應用程序。這是我看到的類似情況下使用WebClient.UploadStringAsync與SL5類似的行爲。

我即將實施/測試我昨天碰到的一種技術,它使用SL中動態構建的「真實」頁面帖子;我會很快彙報我的發現。

更新 - 此方法適用於: http://www.codeproject.com/Tips/392435/Using-HTTP-Form-POST-method-to-pass-parameters-fro

我只是測試它在我的應用程序(內部MVC SL5)和它的作品就好了。確保你檢查HttpContext.Request.Form [「fieldname」]來獲取你想要的值。我使用這種技術來提交JSON,並能夠爲用戶返回生成的Word文檔。

一旦我實現了這個功能,我就可以擺脫我之前嘗試使用的不必要的WebClient。