What is ASP.NET Web API?

ASP.NET Web API is a framework for building HTTP services that can be accessed from a wide range of clients, including browsers, mobile devices, and other servers. It's a part of the ASP.NET family and shares many features with ASP.NET MVC, but it's specifically designed for creating APIs rather than full web pages.

Key Features:

Core Concepts

Controllers

Controllers in Web API are classes that handle incoming HTTP requests. They typically inherit from ApiController.

Example: A Simple Product Controller


using System.Collections.Generic;
using System.Web.Http;
using YourApp.Models; // Assuming you have a Product model

namespace YourApp.Controllers
{
    public class ProductsController : ApiController
    {
        // GET: api/Products
        public IEnumerable<Product> Get()
        {
            // In a real application, this would fetch data from a database
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Laptop", Price = 1200.00M },
                new Product { Id = 2, Name = "Keyboard", Price = 75.50M }
            };
            return products;
        }

        // GET: api/Products/5
        public Product Get(int id)
        {
            // Find product by ID
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Laptop", Price = 1200.00M },
                new Product { Id = 2, Name = "Keyboard", Price = 75.50M }
            };
            return products.Find(p => p.Id == id);
        }

        // POST: api/Products
        public void Post([FromBody]Product product)
        {
            // Add new product to data store
        }

        // PUT: api/Products/5
        public void Put(int id, [FromBody]Product product)
        {
            // Update product with the specified ID
        }

        // DELETE: api/Products/5
        public void Delete(int id)
        {
            // Delete product with the specified ID
        }
    }
}
                

Routing

Routing maps incoming requests to specific controller actions. Web API uses a routing table, similar to MVC, but often simpler for API scenarios.

Example: Default Routing Configuration


// In App_Start/WebApiConfig.cs
using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
                

With the above route, a request to /api/products would map to the ProductsController's Get() method. A request to /api/products/5 would map to ProductsController's Get(int id) method.

HTTP Verbs and Actions

Web API maps HTTP verbs to controller methods based on naming conventions:

You can also use attributes like [HttpGet], [HttpPost], etc., to explicitly define the HTTP method for an action.

Request and Response Formats

Web API's ContentNegotiator automatically handles format selection. By default, it prefers JSON but can also handle XML. Clients can specify their preferred format using the Accept header.

Example: Client Request (using curl)


curl -H "Accept: application/json" http://yourserver.com/api/products
                

The server will respond with JSON data if available.

Building Your First Web API

  1. Create a new ASP.NET Web Application in Visual Studio and select the "Web API" template.
  2. Define your models (e.g., a Product class).
  3. Create a Web API Controller by right-clicking the Controllers folder, selecting Add > Controller, and choosing "Web API Controller - Empty".
  4. Implement HTTP methods (GET, POST, PUT, DELETE) in your controller to handle requests.
  5. Configure routing in WebApiConfig.cs.
  6. Run your application and test your API endpoints using tools like Postman or your browser.

Further Reading