ASP.NET Core API Analyzer

Introduction

 
The ASP.NET Core API analyzer was introduced in ASP.NET Core 2.2 as a NuGet package, as isis used as an analyzer for ASP.NET Core APIs. The analyzer will work with the controller which is decorated with the attribute [ApiController].
 
Tooling
 
Visual Studio 2019
 

Install ASP.NET Core API Analyzer

 
Open Asp.Net Core API project in visual studio, right-click on the solution -> Manage NuGet Packages
 
Select the package source as nuget.org and search for Microsoft.AspNetCore.Mvc.Api.Analyzer and click on install as shown in the below figure or we can use the package manager console (go to view->other windows->package manager console) to install the analyzer using the below command. 
 
Install-Package Microsoft.AspNetCore.Mvc.Api.Analyzers
 
ASP.NET Core API Analyzer
 
Consider the below code:
  1. // PUT: api/Employees/5  
  2.       [HttpPut("{id}")]  
  3.       public async Task<IActionResult> PutEmployee(int id, Employee employee)  
  4.       {  
  5.           if (id != employee.EmployeeID)  
  6.           {  
  7.               return BadRequest();  
  8.           }  
  9.           _context.Entry(employee).State = EntityState.Modified;  
  10.           try  
  11.           {  
  12.               await _context.SaveChangesAsync();  
  13.           }  
  14.           catch (DbUpdateConcurrencyException)  
  15.           {  
  16.               if (!EmployeeExists(id))  
  17.               {  
  18.                   return NotFound();  
  19.               }  
  20.               else  
  21.               {  
  22.                   throw;  
  23.               }  
  24.           }  
  25.           return NoContent();  
  26.       }  
If you generate a document for the above API using swagger, you can see the details only for the status code 200, as shown below. If you generate a document for the above API using swagger, you can see the details only for the status code 200. As shown in the figure, there won’t be any document for status 400 and 404 cases as per the code, which means the swagger needs more metadata to generate the document for all the cases in the action. 
 
ASP.NET Core API Analyzer
 
Once the API Analyzer is installed, you will get a warning for all the return statements of the put action, as shown in the below figure.
 
ASP.NET Core API Analyzer 
 
Based on suggestion provided by the analyzer, add the attribute for the action
 
ASP.NET Core API Analyzer
 
Now run the application and check the document, you can find the detailed documentation for all the cases, 204, 400 and 404.
 
ASP.NET Core API Analyzer
 

Summary

 
In this article, we learned the following things:
  • How to install the Asp.Net Core API Analyzer
  • How and where to use to Asp.Net API Analyzer in the application for documentation