MVC 4 Web Api Post

11,418

You could use the HttpClient to call this method:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://example.com");
    var result = client.PostAsync("/api/performances", new
    {
        id = 1,
        date = DateTime.Now,
        value = 1.5
    }, new JsonMediaTypeFormatter()).Result;
    if (result.IsSuccessStatusCode)
    {
        Console.writeLine("Performance instance successfully sent to the API");
    }
    else
    {
        string content = result.Content.ReadAsStringAsync().Result;
        Console.WriteLine("oops, an error occurred, here's the raw response: {0}", content);
    }
}

In this example I am using the generic PostAsync<T> method allowing me to send any object as second parameter and choose the media type formatter. Here I have used an anonymous object mimicking the same structure as your Performance model on the server and the JsonMediaTypeFormatter. You could of course share this Performance model between the client and the server by placing it in a contracts project so that changes on the server would also be automatically reflected on the client.

Side remark: C# naming convention dictates that method names should start with a capital letter. So getPerformances should be GetPerformances or even better Get and postPerformances should be PostPerformances or even better Post.

Share:
11,418
gsmida
Author by

gsmida

Updated on June 24, 2022

Comments

  • gsmida
    gsmida almost 2 years

    I want to make an insertion from a distant client for that I need to send data via http.
    I can use the getPerformances() correctly with an httpClient api/performances?date={0}

    I want to ask if my postPorformances() implemntation inside my PerformancesController is corrrect and if it is how to call it from a client?

    Here is my implementation:

    public class PerformancesController : ApiController
        {
            // GET api/performances
            public IEnumerable<Performance> getPerformances(DateTime date)
            {
                return DataProvider.Instance.getPerformances(date);
            }
    
            public HttpResponseMessage postPerformances(Performance p)
            {
                DataProvider.Instance.insertPerformance(p);
                var response = Request.CreateResponse<Performance>(HttpStatusCode.Created, p);
                return response;
            }
        }
    
    public class Performance {
        public int Id {get;set;}
        public DateTime Date {get;set;}
        public decimal Value {get;set;}
    }
    

    I have tried this one but I'm note sure:

      private readonly HttpClient _client;
      string request = String.Format("api/performances");
      var jsonString = "{\"Date\":" + p.Date + ",\"Value\":" + p.Value + "}";
      var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
      var message = await _client.PutAsync(request, httpContent);
    
  • BlackTigerX
    BlackTigerX over 8 years
    If the ap/performances call takes a long time, you might want to set the client.Timeout before making the call