Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Web Api Post

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);
like image 409
gsmida Avatar asked Mar 04 '13 13:03

gsmida


People also ask

Can we use Web API in MVC?

If you have used ASP.NET MVC, you are already familiar with controllers. Web API controllers are similar to MVC controllers, but inherit the ApiController class instead of the Controller class. In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.

How do I use FromUri in Web API?

Using [FromUri] To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.


1 Answers

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.

like image 131
Darin Dimitrov Avatar answered Oct 17 '22 14:10

Darin Dimitrov