08-23-2018, 11:17 PM
ASP.NET Core 2.20-preview1: Open API Analyzers & Conventions
What is it?
Open API (alternatively known as Swagger) is a language-agnostic specification for describing REST APIs. The Open API ecosystem has tools that allows for discovering, testing and producing client code using the specification. Support for generating and visualizing Open API documents in ASP.NET Core MVC is provided via community driven projects such as NSwag, and Swashbuckle.AspNetCore. Visit https://docs.microsoft.com/en-us/aspnet/...etcore-2.1 to learn more about Open API Swagger and for details on configuring your applications to use it.
For 2.2, we’re investing in tooling and runtime experiences to to allow developers to produce better Open API documents. This work ties in with ongoing work to perform client code SDK generation during build.
How to use it?
Analyzer
For 2.2, we’re introducing a new API-specific analyzers NuGet package –. These analyzers work with controllers annotated with introduced in 2.1, while building on API conventions that we’re also introducing in this release. To start using this, install the package:
Open API documents contain each status code and response type an operation may return. In MVC, you use attributes such as and to document these. The analyzer inspects controllers annotated with and identifies actions that do not entirely document their responses. You should see this as warnings (squiggly lines) highlighting return types that aren’t documented as well as warnings in the output. In Visual Studio, this should additionally appear under the “Warnings” tab in the “Error List” dialog. You now have the opportunity to address these warnings using code fixes.
Let’s look at the analyzer in action:
The analyzer identified that the action returned a but did not document it using a . We used a code fix to document this. The added attributes would now become available for Swagger / Open API tools to consume. It’s a great way to identify areas of your application that are lacking swagger documentation and correct it.
Conventions
If your controllers follows some common patterns, e.g. they are all primarily CRUD endpoints, and you aren’t already using or to document them, you could consider using API conventions. Conventions let you define the most common “conventional” return types and status codes that you return from your action, and apply them to individual actions or controllers, or all controllers in an assembly. Conventions are a substitute to decorating individual actions with attributes.
By default, ASP.NET Core MVC 2.2 ships with a set of default conventions – – that’s based on the controller that ASP.NET Core scaffolds. If your actions follow the pattern that scaffolding produces, you should be successful using the default conventions.
At runtime, ApiExplorer understand conventions. ApiExplorer is MVC’s abstraction to communicate with Open API document generators. Attributes from the applied convention get associated with an action and will be included in action’s Swagger documentation. API analyzers also understand conventions. If your action is unconventional i.e. it returns a status code that is not documented by the applied convention, it will produce a warning, encouraging you to document it.
There are 3 ways to apply a convention to a controller action:
Like many other features in MVC, more specific attributes will supersede less specific ones. An API metadata attribute such as or applied to an action will stop applying any convention atributes. The will supersede a attribute applied to the method’s controller or the assembly; and an attribute applied to a controller will supersede ones applied to the assembly.
Authoring conventions
A convention is a static type with methods. These methods are annotated with or attributes.
Applying this convention to an assembly would result in the convention method applying to any action with the name and having exactly one parameter named , as long as they do not have other more specific metadata attributes.
In addition to and , two additional attributes – and – can be applied to the convention method that determines the methods they apply to.
The applied to the method, indicates that the convention can match any action as long as it starts with the prefix “Find”. This will include methods such as , or . The applied to the parameter, indicates that the convention can match methods with exactly one parameter that terminate in the suffix . This will include parameters such as , or . can be similarly applied to types to constrain the type of the parameter. A arguments can be used to indicate remaining parameters that do not need not be explicitly matched.
An easy way to get started authoring a custom convention is to start by copying the body of and modifying it. Here’s a link to the source of the type: https://raw.githubusercontent.com/aspnet...entions.cs
Feedback
This is one on our earliest forays in trying to use tooling to enhance runtime experiences. We’re interested in any thoughts you have about this as well as your experiences using this in your applications. The best place to provide feedback is by opening issues at https://github.com/aspnet/Mvc.
Additional help
What is it?
Open API (alternatively known as Swagger) is a language-agnostic specification for describing REST APIs. The Open API ecosystem has tools that allows for discovering, testing and producing client code using the specification. Support for generating and visualizing Open API documents in ASP.NET Core MVC is provided via community driven projects such as NSwag, and Swashbuckle.AspNetCore. Visit https://docs.microsoft.com/en-us/aspnet/...etcore-2.1 to learn more about Open API Swagger and for details on configuring your applications to use it.
For 2.2, we’re investing in tooling and runtime experiences to to allow developers to produce better Open API documents. This work ties in with ongoing work to perform client code SDK generation during build.
How to use it?
Analyzer
For 2.2, we’re introducing a new API-specific analyzers NuGet package –
Code:
Microsoft.AspNetCore.Mvc.Api.AnalyzersCode:
ApiControllerCode:
<PackageReference Include="Microsoft.AspNetCore.Mvc.Api.Analyzers"
Version="2.2.0-preview1-35029"
PrivateAssets="All" />Open API documents contain each status code and response type an operation may return. In MVC, you use attributes such as
Code:
ProducesResponseTypeCode:
ProducesCode:
ApiControllerLet’s look at the analyzer in action:
The analyzer identified that the action returned a
Code:
404Code:
ProducesResponseTypeAttributeConventions
If your controllers follows some common patterns, e.g. they are all primarily CRUD endpoints, and you aren’t already using
Code:
ProducesResponseTypeCode:
ProducesCode:
ProducesResponseTypeBy default, ASP.NET Core MVC 2.2 ships with a set of default conventions –
Code:
DefaultApiConventionsAt runtime, ApiExplorer understand conventions. ApiExplorer is MVC’s abstraction to communicate with Open API document generators. Attributes from the applied convention get associated with an action and will be included in action’s Swagger documentation. API analyzers also understand conventions. If your action is unconventional i.e. it returns a status code that is not documented by the applied convention, it will produce a warning, encouraging you to document it.
There are 3 ways to apply a convention to a controller action:
- Applying the attribute as an assembly level attribute. This applies the specified convention to all controllers in an assembly.Code:
ApiConventionType
Code:
[assembly: ApiConvention(typeof(DefaultApiConventions))]- Using the attribute on a controller.Code:
ApiConventionType
Code:
[ApiConvention(typeof(DefaultApiConventions))]
[ApiController]
[Route("/api/[controller]")]
public class PetsController : ControllerBase
{ ...
}- Using . This attributes accepts both the type and the convention method.Code:
ApiConventionMethod
Code:
// PUT: api/Pets/5
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Put))]
[HttpPut("{id}")]
public async Task<ActionResult<Pet>> PutPet(long id, Pet pet)
{ ...
}Like many other features in MVC, more specific attributes will supersede less specific ones. An API metadata attribute such as
Code:
ProducesResponseTypeCode:
ProducesCode:
ApiConventionMethodCode:
ApiConventionTypeCode:
ApiConventionTypeAuthoring conventions
A convention is a static type with methods. These methods are annotated with
Code:
ProducesResponseTypeCode:
ProducesDefaultResponseTypeCode:
public static class MyAppConventions
{ [ProducesResponseType(200)] [ProducesResponseType(404)] public static void Find(int id) {
}
}Applying this convention to an assembly would result in the convention method applying to any action with the name
Code:
FindCode:
idIn addition to
Code:
ProducesResponseTypeCode:
ProducesDefaultResponseTypeCode:
ApiConventionNameMatchCode:
ApiConventionTypeMatchCode:
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
public static void Find( [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Suffix)] int id)
{ }The
Code:
ApiConventionNameMatchBehavior.PrefixCode:
FindCode:
FindPetCode:
FindByIdCode:
ApiConventionNameMatchBehavior.SuffixCode:
idCode:
idCode:
petIdCode:
ApiConventionTypeMatchCode:
params[]An easy way to get started authoring a custom convention is to start by copying the body of
Code:
DefaultApiConventionsFeedback
This is one on our earliest forays in trying to use tooling to enhance runtime experiences. We’re interested in any thoughts you have about this as well as your experiences using this in your applications. The best place to provide feedback is by opening issues at https://github.com/aspnet/Mvc.
Additional help

