Monday 22 August 2016

Getting Started with ASP.NET Web API 2 (C#) Part 2

We finished the first part of this series with creating an in-memory data source and a Get() API method. 
The Get method returned the full list of ProductList records in the data repository.


We are ready to move on to other aspects of this technology. So open the demo project we started previously. We’re going to look at the following elements:

  1. Action method: get element by ID
  2. Routing by attributes
  3. Returning IHttpActionResult from controller action
  4. Cross origin resource sharing

Get an element by id

Now we can retrieve all elements in from the API in an XML string. We also want to be able to get a single item by its ID.
and the output we want by id and it will look like this.

So Now Open ProductController.cs and add the following stub:


We’ll be able to reach this action by the URL /api/product/{id}. It couldn’t be easier. The most obvious way is to add the following method to InMemoryDataContext.cs:

The body of the Get(id) method will be as follows:
Run the application and navigate to /api/product/1. You should get the XML representation of the ProductListwhose ID is 1:


What happens if you type an ID of a nonexistent productlist, such as 8? You’ll get a null XML back:

Let’s make this a bit more obvious to the caller. Change the signature of the Get(id) method to return an HttpResponseMessage instead of a productlist:


This object allows us to control the response message we return to the caller of the Get(id) method: the response code, the headers, the message content, i.e. all elements of a standard HTTP response. It is customary to let Web API actions return this object. In the body of the action we can return a 404 if the item wasn’t found. Otherwise we return a 200 OK with the ProductList object. Here’s one way to solve this:

Re-run the demo app, try to get a productlist with an ID of 8 and you should get a XML formatted error message:

The next operation that would be nice to implement is to retrieve the albums of a productlist by the URL api/productlist/3/albums. Routing of such URLs in the previous version of the Web API was a bit tricky. You could set up your custom routes in WebApiConfig.cs, but it could get messy if you wanted to support extended urls beyond the basic /api/{controller}/{id} format. However, in Web API 2 there’s a different way.

We will see that in next Post.



0 comments:

Post a Comment