Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient PutAsync doesn't send a parameter to api

On the controller Put is as following:

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

The issue is on the when consuming this API via following

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;
    }

This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.

like image 253
fcmaine Avatar asked May 07 '12 21:05

fcmaine


2 Answers

For me it worked correctly:

            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
            }
like image 82
Pablo Avatar answered Nov 12 '22 01:11

Pablo


Here is what works for me:

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);

and my action method:

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

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

and the model

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

-Stan

like image 27
Stan Bashtavenko Avatar answered Nov 12 '22 01:11

Stan Bashtavenko