2012-05-07 134 views
6

在把控制器如下:HttpClient的PutAsync不參數發送到API

[HttpPut] 
[ActionName("putname")] 
public JsonResult putname(string name) 
{ 
    var response = ... 
    return Json(response); 
} 

的問題是在通過以下

using (httpClient = new HttpClient()) 
{ 
    string name = "abc"; 
    string jsonString = JsonConvert.SerializeObject(name); 
    var requestUrl = new Uri("http:...../controller/putname/"); 
    using (HttpContent httpContent = new StringContent(jsonString)) 
    { 
     httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
     HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result; 
    } 

消耗這個API時,該代碼沒有按」將參數名稱傳遞給控制器​​。我甚至嘗試量變到質變的URI/putname /」 +名

回答

16

這裏是什麼對我的作品。

var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}"; 
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");    
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent); 
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode); 

和我的操作方法:

public void PutRate(AppRating model) 
{ 
    if (model == null) 
     throw new HttpResponseException(HttpStatusCode.BadRequest); 

    if (ModelState.IsValid) 
    { 
    // .. 
    }  
} 

和模型

public class AppRating 
{ 
    public int AppId { get; set; } 
    public int PlatformId { get; set; } 
    public decimal Rating { get; set; } 
} 

-Stan

+0

感謝您的答覆。我認爲你所說的應該起作用。以下是我所做的。 var cUri = new Uri(「http:// localhost/cart/coupon」); var jsonString = JsonConvert.SerializeObject(new {id =「abc」}); HttpResponseMessage cartResponse; (HttpContent httpContent = new StringContent(jsonString)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue(「application/json」); cartResponse = httpClient.PostAsync(cUri,httpContent).Result; } – fcmaine

+0

我用同樣的東西,你建議作爲答案,但不工作。 –

+0

不錯,這也適用於我 –

0

對我來說它工作正常:

  string requestUrl = endpointUri + "/Files/"; 
      var jsonString = JsonConvert.SerializeObject(new { name = "newFile.txt", type = "File" }); 

      HttpContent httpContent = new StringContent(jsonString); 
      httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json");   

      HttpClient hc = new HttpClient(); 

      //add the header with the access token 
      hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); 

      //make the put request 
      HttpResponseMessage hrm = (await hc.PostAsync(requestUrl, httpContent)); 

      if (hrm.IsSuccessStatusCode) 
      { 
       //stuff 
      }