ASP.NET Core Web API
This documentation provides a comprehensive guide to building Web APIs with ASP.NET Core. ASP.NET Core Web API is a framework for building HTTP services that can be accessed from a broad range of clients, including browsers and mobile devices.
Introduction to Web API
Web API allows you to build RESTful services and applications. It's built on the same ASP.NET Core infrastructure as MVC applications, providing a powerful and flexible way to expose data and functionality over HTTP.
Key features include:
- Support for various data formats (JSON, XML).
- Content negotiation.
- Routing and attribute routing.
- Model binding and validation.
- Dependency injection.
- Cross-Origin Resource Sharing (CORS).
Getting Started
To start building a Web API, you can create a new ASP.NET Core Web API project in Visual Studio or using the .NET CLI:
dotnet new webapi -o MyWebApiProject
cd MyWebApiProject
This will create a basic project structure with controllers ready to be implemented.
Controllers
Controllers are classes that handle incoming HTTP requests. They typically inherit from ControllerBase
and contain action methods that map to specific HTTP verbs and routes.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public ActionResult> Get()
{
return new string[] { "Product 1", "Product 2" };
}
[HttpGet("{id}")]
public ActionResult Get(int id)
{
if (id <= 0) return BadRequest("Product ID must be positive.");
return $"Product {id}";
}
}
Routing
ASP.NET Core Web API supports two main routing approaches:
- Convention-based routing: Defined in the
Program.cs
(orStartup.cs
) file. - Attribute routing: Defined using attributes on controllers and action methods (e.g.,
[Route("api/[controller]")]
,[HttpGet("details/{id}")]
). Attribute routing is generally preferred for Web APIs as it allows for more explicit and organized routing configurations.
Model Binding and Validation
Web API automatically binds incoming request data (query parameters, route parameters, request body) to controller action parameters. Validation can be performed using data annotation attributes.
public class CreateProductRequest
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Range(1, 1000)]
public decimal Price { get; set; }
}
[HttpPost]
public IActionResult CreateProduct([FromBody] CreateProductRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// ... create product logic
return Ok();
}
API Reference
Here's a quick reference for common HTTP status codes used in Web APIs:
Code | Reason Phrase | Description |
---|---|---|
200 | OK | The request succeeded. |
201 | Created | The request succeeded and a new resource was created. |
204 | No Content | The request succeeded but there was no response body. |
400 | Bad Request | The request was invalid or could not be processed. |
401 | Unauthorized | Authentication is required and has failed or has not yet been provided. |
403 | Forbidden | The server understood the request, but refuses to authorize it. |
404 | Not Found | The requested resource could not be found. |
500 | Internal Server Error | An unexpected error occurred on the server. |