MVC 4 Web Api Post

I want to do an insertion from a remote client, because I need to send data via http.
I can use correctly getPerformances()withhttpClient api/performances?date={0}

I want to ask if my implementation postPorformances()inside mine is correct PerformancesController, and how to call it from the 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, but I am sure that:

  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);
+5
source share
1 answer

You can use HttpClientto 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 the raw response: {0}", content);
    }
}

PostAsync<T>, - . , , Performance , JsonMediaTypeFormatter. , Performance , , .

: # , . getPerformances getPerformances Get, postPerformances postPerformances Post.

+10

All Articles