HttpClient PutAsync不会向api发送参数

时间:2012-05-07 21:46:42

标签: c# asp.net-mvc-3 json.net

在控制器上,Put如下:

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

问题在于通过以下

消费此API时的问题
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;
    }

此代码未将参数名称传递给控制器​​。我甚至尝试将uri更改为/ putname /“+ name。

2 个答案:

答案 0 :(得分:24)

这对我有用:

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

答案 1 :(得分: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
            }