2016-03-02 54 views
0

誰能告訴我爲什麼HttpClientPostAsync不張貼表單數據?HttpClient不張貼表單數據

我在客戶端發佈時沒有收到服務器端的數據。上次我檢查時,formFields包含鍵值對中的數據,但無法找到formContent中的數據。

using (var client = new HttpClient()) 
{ 
    var formFields = new List<KeyValuePair<string, string>>(); 

    formFields.Add(new KeyValuePair<string, string>("AccountId", _dealerAccountId)); 
    formFields.Add(new KeyValuePair<string, string>("Username", _dealerUsername)); 
    formFields.Add(new KeyValuePair<string, string>("Password", _dealerPassword)); 

    var formContent = new FormUrlEncodedContent(formFields); 
    var response = await client.PostAsync(httpPrefix + "://" + httpHost + "/WebApi/Token/GetToken_v1/1592673/", formContent); 
    if (!response.IsSuccessStatusCode) 
    { 
     return; 
    } 
    var responseContent = await response.Content.ReadAsStringAsync(); 

    token = JsonConvert.DeserializeObject<string>(responseContent); 
} 
+0

對我來說這看起來很好。你確定數據沒有被髮布,並且問題不在於你如何在服務器上接收數據?後端是否有一些ASP.NET的味道?你可以發佈並描述你如何驗證沒有收到數據? –

回答

0

我依稀記得有類似的問題。我們最終沒有使用「PostAsync」方法,但使用了以下內容。這是我們用來測試我們的WebAPI的輔助方法。希望這可以幫助。

public async Task<TestHttpResponseMessage> Post(string url, string jsonPayload = "", Dictionary<string, string> headers = null, IFilter filter = null, HttpContent content = null) 
{ 
    using (var server = CreateTestserver(filter)) 
    { 
     if (!url.StartsWith("http")) 
      url = "http://localhost/" + url; 

     var request = new HttpRequestMessage 
     { 
      RequestUri = new Uri(url), 
      Method = HttpMethod.Post, 
      Content = content ?? new StringContent(jsonPayload, Encoding.UTF8, "application/json") 
     }; 

     request.Headers.Add("usertoken", OpenApiApplication.TestApiKey.ToString()); 

     if (headers == null) 
      headers = new Dictionary<string, string>(); 

     foreach (var header in headers) 
      request.Content.Headers.Add(header.Key, header.Value); 

     var httpResponseMessage = await server.HttpClient.SendAsync(request); 

     var stringResult = await httpResponseMessage.Content.ReadAsStringAsync(); 

     return new TestHttpResponseMessage { JsonObject = Json.Decode(stringResult), HttpResponseMessage = httpResponseMessage }; 
    } 
} 
+1

它看起來像OP正試圖模擬一個表單帖子。您的代碼發佈JSON有效內容和自定義標頭。不知道這是如何幫助。 –

+0

用您的FormUrlEncodedContent替換StringContent。我只是想告訴你我們是如何得到這個工作的,而不是用「PostAsync」 –