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
Consider the below code:
-
- [HttpPut("{id}")]
- public async Task<IActionResult> PutEmployee(int id, Employee employee)
- {
- if (id != employee.EmployeeID)
- {
- return BadRequest();
- }
- _context.Entry(employee).State = EntityState.Modified;
- try
- {
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!EmployeeExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return NoContent();
- }
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.
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.
Based on suggestion provided by the analyzer, add the attribute for the action
Now run the application and check the document, you can find the detailed documentation for all the cases, 204, 400 and 404.
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