Database Reference
In-Depth Information
private async Task PutOrderAsync()
{
// construct call to generate HttpPut verb and dispatch
// to corresponding Put method in the Web API Service
var response = await _client.PutAsJsonAsync("api/order", _order);
if (response.IsSuccessStatusCode)
{
// capture updated order returned from service, which will include new quanity
_order = await response.Content.ReadAsAsync<Order>();
Console.WriteLine("Successfully updated order: {0}", response.StatusCode);
}
else
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
private async Task RemoveOrderAsync()
{
// remove order
var uri = "api/order/" + _order.OrderId;
var response = await _client.DeleteAsync(uri);
if (response.IsSuccessStatusCode)
Console.WriteLine("Sucessfully deleted order: {0}", response.StatusCode);
else
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
The following is the output of our test client from Listing 9-6:
Successfully created order: http://localhost:3237/api/order/1054
Successfully updated order: OK
Sucessfully deleted order: OK
How It Works
Start by running the Web API application. The Web API application contains an MVC Web Controller that, when
started, will bring up a home page. At this point, the site is running and its services are available.
Next open the console application, set a breakpoint on the first line of code in the program.cs file, and run the
console application. First we establish some basic plumbing—mapping the Web API service URI and configuring
the Accept Header —that will ask the Web API service to return the data in a JSON format. Then we create an Order
object, which we send to the Web API service by calling the PostAsJsonAsync method from the HttpClient object.
If you place a breakpoint in the Post Action Method in the Order Web API controller class, you'll see that it receives
the order object as a parameter and adds it to the Order entity in the context object. Doing so marks the object as
added and causes the context to start tracking it. Finally, we call the SaveChanges method to insert the new data into
the underlying data store. We then wrap a HTTP status code of 201 and the URI location of the newly created resource
into an HttpResponseMessage object and return it to the calling application. When using the ASP.NET Web API, we
want to ensure that our client generates an HTTP Post verb when inserting new data. The HTTP Post verb will invoke
the corresponding Post action method in the Web API controller.
 
 
Search WWH ::




Custom Search