Creating our first ASP.NET web API

In this recipe, we will see how to expose a basic service and some data through HTTP with the ASP.NET web API.

Getting ready

In order to use this recipe, you should have Visual Studio 2012 and ASP.NET MVC 4 installed (the latter one includes the ASP.NET web API).

How to do it...

Next we are going to create a web API:

  1. To start, open Visual Studio 2012, select the web category from the visual C# categories and use the ASP.NET MVC 4 Web Application template to create a new project. Name it WebAPI101.
  2. On the New ASP.NET MVC 4 Project dialog select the Web API template and click on the OK button.
    How to do it...

    The following project structure will be created for us:

    How to do it...
  3. In the Models folder we will add a class, name it Booksmodel.cs, and introduce the following code:
    public class BookModel
    {
    Public int Id { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public bool IsOnSale { get; set; }
    public int BookRating { get; set; }
    public double BookPrice { get; set; }
    }
  4. Next, we will add our own controller; right-click on the Controllers folder, select Add, and then left-click over the Controller... option, as shown in the following screenshot:
    How to do it...
  5. In the Controller dialog in Add, give it the name BooksController, select the Empty API Controller template, and click on the Add button.
    How to do it...
  6. We could have started by opening the ValuesController.cs file and customizing it, but it is better to delete this file so that we can illustrate the entire process.
  7. Open the BooksController.cs file and change the code of the BooksController class to the following:
    public class BooksController : ApiController
    {
        BookModel[] Books = null;
        public BooksController()
        {
            Books = GenerateBooks();
        }
        public IEnumerable<BookModel> Get()
        {
            return Books;
        }
        public BookModel Get(int id)
        {
            var book = (from b in Books
                        where b.Id == id
                        select b).FirstOrDefault();
            return book;
        }
        private BookModel[] GenerateBooks() {
            BookModel[] Books = new BookModel[] { 
                new BookModel(){
                        Id=1,
                        Title = ".NET 4.5 First Look",
                        Description = "A book to quickly and practically get into .NET 4.5"
                },
                new BookModel(){
                        Id=2,
                        Title = "The lost book of Agatha Christie",
                        Description = "A book everybody wants to read..."
                }
            };
            return Books;
        }
    }
  8. Press F5 to debug the application.
  9. In the URL, add api/books/, so it will look similar to http://localhost:19347/api/books/ and press Enter. Please note that the port number might change.
  10. If we are opening the web page with Internet Explorer, we should see the following message:
    How to do it...
  11. We will open it with Notepad, and our content will be as follows:
    [{"Id":1,"Title":".NET 4.5 First Look","Description":"A book to quickly and practically get into .NET 4.5","IsOnSale":false,"BookRating":0,"BookPrice":0.0},{"Id":2,"Title":"The lost book of Agatha Christie","Description":"A book everybody wants to read...","IsOnSale":false,"BookRating":0,"BookPrice":0.0}]
  12. This is the response from our web API. If we open it with another browser, such as Mozilla Firefox or Google Chrome, we will see it as an XML visualization:
    How to do it...
  13. Note that to run it on another browser, we have to expand the browser dropdown located on the DEBUG button, as follows:
    How to do it...
  14. The response is so browser dependent because our web API is sending different content types due to the Accept section in the request headers. We are getting a JSON response for IE and an XML response for other browsers.
  15. An interesting step here would be to test the browser tools (for Internet Explorer and for Google Chrome) and see the http network traffic, specifically the request headers and returned types for each browser.
  16. We could go on and explore the web API to get a single book, filtering by its ID. Execute the application with Firefox, go to the URL, add api/books/1 to it, so it will look similar to http://localhost:19347/api/books/1, and press Enter. We should get the following response:
    How to do it...

With these few steps we have created a very simple ASP.NET Web API and tested it with a browser.

How it works...

We created an ASP.NET web API from its ASP.NET MVC 4 template, where we built a model to define the information to be exposed through the web API, and then went on to create the controller.

A web API controller is derived from the ApiController class. Its main function is to prepare, filter, and return the requested information.

It is important to note the routing concept in web API, where there is a mapping of the URL to the methods we expose in the controller class, resulting in the routes:

  • /api/Books:Get()
  • /api/Books:Get(1)

If we explore the RouteConfig.cs file, in the App_Start folder, we will observe that some mappings have been added, such as api/{controller}/{id}, where {controller} and {id} are placeholders.

The mapping process works as follows: the web API framework decides which API controller will handle the request by matching {placeholder} to the controller's name. Then the placeholder {id} is matched to a parameter of the same name.

In our case, Books is matched to BooksController. Since the request is a GET, it looks for a method that starts with Get and has no parameters; therefore, it is matched to Get(). However, we could have given it the name GetBooks() or GetAllBooks() and the result would have been the same. Finally, when we put in an extra parameter for the ID, the web API framework looks for a matching GET method that has an ID parameter, which matches our Get(int id) as a result.

Next, we have created the GenerateBooks() method, which we call on the constructor of our BooksController class, the Get() method that returns the whole array of books, and the Get(int id) function that returns only the book with the requested ID.

We have tested our web API from our browser, to get the full list of books and then a specific book.

There's more...

This is of course a very basic view of the web API and we have left plenty of interesting areas to explore, such as creating web API clients, routing and actions, custom formats, model binding, hosting aspects, OData support, extensibility features, testing, and debugging capabilities.

See also

  • Implementing a CRUD ASP.NET Web API
  • Setting up a self-hosted ASP.NET Web API
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset