CS296N Web Development 2: ASP.NET
Brian Bird

Topic: Implementing a REST Web API in ASP.NET Core

Topics
1. Intro to course and Identity
6. Load Testing and Performance, Midterm Quiz
2. Authentication and Authorization 7. Creating a Web Service
3. Claims and Third Party Authentication
8. Consuming a Web Service, Async / Await
4. Web Security
9. Docker Containers
5. Publishing to a Production Server 10.  Microservices

Introduction

Last time we talked about web services in general. Today, we'll look at how to implement one using ASP.NET Core. The approach we're using follows the example in our textbook (Freeman, 2017). It's a little different from the approach shown in the Microsoft Tutorial

Implementation

Controller

Each action method should have the route annotation below so that the method names don't need to be included in the URL
[Route("api/[controller]")]
URL will be: http://localhost:5000/api/Book/

Controller Methods

There will be one method for each HTTP verb. You can write the method using an ActionMethod or IActionMethod return type, but just return a POCO object and MVC will figure out the correct format for the returned data--including the HTTP status code. But, you can also explicitly determine the status code.

Status Codes

Each of the methods returns an IActionResult which allows the use of StatusCode helper methods. HTTP Status codes, along with the available status code helper methods are shown below:

Examples

The HTTP verb, an example HTTP request and a controller method are shown below.

Notes

  1. In ASP.NET Core version 2.1 and later, use of the [ApiController] annotation is no longer needed on a controller class that will provide API endpoints.
  2. Your controller can be a subclass of Controller, but it is better to make it a subclass of ControllerBase (Controller inherits from this) since Controller contains View related members that you don't need.
  3. Source code on GitHub: ProfBird/BookInfo-Core-2-WebAPI
  4. Web service running online: BookInfo Service

References