20 Creating an HTTP API using web API controllers

 

This chapter covers

  • Creating a web API controller to return JavaScript Object Notation (JSON) to clients
  • Using attribute routing to customize your URLs
  • Generating a response using content negotiation
  • Applying common conventions with the [ApiController] attribute

In chapters 13 through 19 you worked through each layer of a server-side rendered ASP.NET Core application, using Razor Pages and Model-View-Controller (MVC) controllers to render HTML to the browser. In part 1 of this book you saw a different type of ASP.NET Core application, using minimal APIs to serve JSON for client-side SPAs or mobile apps. In this chapter you’ll learn about web API controllers, which fit somewhere in between!

You can apply much of what you’ve already learned to web API controllers; they use the same routing system as minimal APIs and the same MVC design pattern, model binding, and validation as Razor Pages and MVC controllers.

In this chapter you’ll learn how to define web API controllers and actions, and see how similar they are to the Razor Pages and controllers you already know. You’ll learn how to create an API model to return data and HTTP status codes in response to a request, in a way that client apps can understand.

20.1 Creating your first web API project

20.2 Applying the MVC design pattern to a web API

20.3 Attribute routing: Linking action methods to URLs

20.3.1 Combining route attributes to keep your route templates DRY

20.3.2 Using token replacement to reduce duplication in attribute routing

20.3.3 Handling HTTP verbs with attribute routing

20.4 Using common conventions with [ApiController]

20.5 Generating a response from a model

20.5.1 Customizing the default formatters: Adding XML support

20.5.2 Choosing a response format with content negotiation