Language

Your First ASP.NET Web API (C#)

By |

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.

Download the completed project.

This tutorial requires Visual Studio with ASP.NET MVC 4. You can use any of the following:

  • Visual Studio 2012
  • Visual Studio Express 2012 for Web
  • Visual Studio 2010 with ASP.NET MVC 4 installed.
  • Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.

If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately. The screenshots in this tutorial show Visual Studio Express 2012 for Web.

Create a Web API Project

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project "HelloWebAPI" and click OK.

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

Adding a Model

A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

Let's start by creating a simple model that represents a product.

If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.

Name the class "Product". Next, add the following properties to the Product class.

namespace HelloWebAPI.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

Adding a Controller

A controller is an object that handles HTTP requests. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.

  • HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to Web API.
  • ValuesController is an example WebAPI controller.

Note  If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

Go ahead and delete ValuesController, by right-clicking the file in Solution Explorer and selecting Delete.

Add a new controller, as follows:

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

In the Add Controller wizard, name the controller "ProductsController". In the Template drop-down list, select Empty API Controller. Then click Add.

The Add Controller wizard will create a file named ProductsController.cs in the Controllers folder.

It is not necessary to put your contollers into a folder named Controllers. The folder name is not important; it is simply a convenient way to organize your source files. 

If this file is not open already, double-click the file to open it. Replace the code in this file with the following:

using HelloWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace HelloWepAPI.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }
    }
}

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.

The controller defines two methods that return products:

  • The GetAllProducts method returns the entire list of products as an IEnumerable<Product> type.
  • The  GetProductById method looks up a single product by its ID.

That's it! You have a working web API.  Each method on the controller maps to a URI:

Controller Method URI
GetAllProducts /api/products
GetProductById /api/products/id

A client can invoke the method by sending an HTTP GET request to the URI. Later, we'll look at how this mapping is done. But first, let's try it out.

Calling the Web API from the Browser

You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.

In Visual Studio, choose Start Debugging from the Debug menu, or use the F5 keyboard shortcut.  The ASP.NET Development Server will start, and a notification will appear in the bottom corner of the screen showing the port number that it is running under. By default, the Development Server chooses a random port number.

Visual Studio will then automatically open a browser window whose URL points to http//www.localhost:xxxx/, where xxxx is the port number. The home page should look like the following:

This home page is an ASP.NET MVC view, returned by the HomeController class.  To invoke the web API, we must use one of the URIs listed previously. For example, to get the list of all products, browse to http://localhost:xxxx/api/products/. (Replace "xxxx" with the actual port number.)

The exact result depends on which web browser you are using. Internet Explorer will prompt you to open or save a "file" named products.

This "file" is actually just the body of the HTTP response. Click Open. In the Open with dialog, select Notepad. Click OK, and when prompted, click Open. The file should contain a JSON representation of the array of products:

[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":
"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":
"Hardware","Price":16.99}]

Mozilla Firefox, on the other hand, will display the list as XML in the browser.

The reason for the difference is that Internet Explorer and Firefox send different Accept headers, so the web API sends different content types in the response.

Now try browsing to http://localhost:xxxx/api/products/1. This request should return the entry with ID equal to 1.

Calling the Web API with Javascript and jQuery

In the previous section, we invoked the web API directly from the browser. But most web APIs are meant to be consumed programmatically by a client application. So let's write a simple javascript client.

In Solution Explorer, expand the Views folder, and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Replace everything in this file with the following:

<div id="body">
    <section class="content-wrapper main-content clear-fix">
        <div>
            <h2>All Products</h2>
            <ul id="products" />
        </div>
        <div>
            <h2>Search by ID</h2>
            <input type="text" id="prodId" size="5" />
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
    </section>
</div>

@section scripts {
<script>
    var apiUrl = 'api/products';

    $(document).ready(function () {
        // Send an AJAX request
        $.getJSON(apiUrl)
            .done(function (data) {
                // On success, 'data' contains a list of products.
                $.each(data, function (key, item) {
                    // Add a list item for the product.
                    $('<li>', { text: formatItem(item) }).appendTo($('#products'));
                });
            });
    });

    function formatItem(item) {
        return item.Name + ': $' + item.Price;
    }

    function find() {
        var id = $('#prodId').val();
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
                $('#product').text(formatItem(data));
            })
            .fail(function (jqXHR, textStatus, err) {
                $('#product').text('Error: ' + err);
            });
    }
</script>
}

Getting a List of Products

To get a list of products, send an HTTP GET request to "/api/products".

The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(apiUrl)
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

Getting a Product By ID

To get a product by ID, send an HTTP GET  request to "/api/products/id", where id is the product ID.

    function find() {
        var id = $('#prodId').val();
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
                $('#product').text(formatItem(data));
            })
            .fail(function (jqXHR, textStatus, err) {
                $('#product').text('Error: ' + err);
            });
    }

We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

Running the Application

Press F5 to start debugging the application. The web page should look like the following:

It's not the best in web design, but it shows that our HTTP service is working. You can get a product by ID by entering the ID in the text box:

If you enter an invalid ID, the server returns an HTTP error:

Understanding Routing

This section explains briefly how ASP.NET Web API maps URIs to controller methods. For more detail, see Routing in ASP.NET Web API.

For each HTTP message, the ASP.NET Web API framework decides which controller receives the request by consulting a route table. When you create a new Web API project, the project contains a default route that looks like this:

/api/{controller}/{id}

The {controller} and {id} portions are placeholders. When the framework sees a URI that matches this pattern, it looks for a controller method to invoke, as follows:

  • {controller} is matched to the controller name.
  • The HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.)
  • {id}, if present, is matched to a method parameter named id.
  • Query parameters are matched to parameter names when possible

Here are some example requests, and the action that results from each, given our current implementation.

URI HTTP Method Action
/api/products GET GetAllProducts()
/api/products/1 GET GetProductById(1)

In the first example, "products" matches the controller named ProductsController. The request is a GET request, so the framework looks for a method on ProductsController whose name starts with "Get...". Furthermore, the URI does not contain the optional {id} segment, so the framework looks for a method with no parameters. The ProductsController.GetAllProducts method meets all of these requirements.

The second example is the same, except that the URI contains the {id} portion. Therefore, the frameworks calls GetProduct, which takes a parameter named id. Also, notice that value "5" from the URI is passed in as the value of the id parameter. The framework automatically converts the "5" to an int type, based on the method signature.

Here are some requests that cause routing errors:

URI HTTP Method Action
/api/products/ POST 405 Method Not Allowed
/api/users/ GET 404 Not Found
/api/products/abc GET 400 Bad Request

In the first example, the client sends an HTTP POST request. The framework looks for a method whose name starts with "Post..." However, no such method exists in ProductsController, so the framework returns an HTTP response with status 405, Method Not Allowed.

The request for /api/users fails because there is no controller named UsersController. The request for api/products/abc fails because the URI segment "abc" cannot be converted into the id parameter, which expects an int value.

Using F12 to View the HTTP Request and Response

When you are working with an HTTP service, it can be very useful to see the HTTP request and request messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:

Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested "application/json" in the Accept header.

If you click the Response body tab, you can see how the product list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. You can use Fiddler to view your HTTP traffic, and also to compose HTTP requests, which gives you full control over the HTTP headers in the request.

Next Steps

Mike Wasson

By Mike Wasson, Mike Wasson is a programmer-writer at Microsoft.

Table of Contents

Getting Started with ASP.NET Web API

Creating Web APIs

Web API Clients

Web API Routing and Actions

Working with HTTP

Formats and Model Binding

OData Support in ASP.NET Web API

Security

Hosting ASP.NET Web API

Testing and Debugging

Extensibility

Resources