.NET Web API: Getting Started
Learn the fundamental concepts of building HTTP services with ASP.NET Web API.
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:
- RESTful Principles: Built with REST (Representational State Transfer) in mind, promoting a stateless, client-server architecture.
- HTTP Verbs: Leverages standard HTTP verbs like GET, POST, PUT, DELETE for performing operations.
- Content Negotiation: Supports various content formats like JSON and XML automatically.
- Routing: Flexible routing engine to map URLs to controller actions.
- Controllers: Similar to MVC, uses controllers to handle incoming requests.
- Model Binding and Validation: Built-in support for binding request data to model objects and performing validation.
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:
GETmaps to methods starting withGet.POSTmaps to methods starting withPost.PUTmaps to methods starting withPut.DELETEmaps to methods starting withDelete.
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
- Create a new ASP.NET Web Application in Visual Studio and select the "Web API" template.
- Define your models (e.g., a
Productclass). - Create a Web API Controller by right-clicking the Controllers folder, selecting Add > Controller, and choosing "Web API Controller - Empty".
- Implement HTTP methods (GET, POST, PUT, DELETE) in your controller to handle requests.
- Configure routing in
WebApiConfig.cs. - Run your application and test your API endpoints using tools like Postman or your browser.