.Net Core Web API 版本控制
.NET Core allows you to control versions of your APIs. To do so you need the following NuGet package:
But lets try to version our API.
STEP 1: CREATE A CONTROLLER
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
using Microsoft.AspNetCore.Mvc;using System;namespace Controllers.V1{ [Route("v{version:apiVersion}/[controller]")] public class HelloWorldController : Controller { [HttpGet] public async Task<IActionResult> HelloWorld() { // This is a stupid example, but just an example. // You would of course have a real async method here return await Task.Run(() => Ok("Hello world")); } }} |
Notice how I in line 6 defines the route as v{version:apiVersion}/[controller]? The {version:apiVersion} will define the versioning that we use later on.
STEP 2: ADD VERSIONING TO THE SERVICES
In your startup code, add the versioning to the services:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
using Microsoft.AspNetCore.Mvc.Versioning;using Microsoft.AspNetCore.Mvc;......services.AddApiVersioning( options => { options.ReportApiVersions = true; options.Conventions.Controller<Controllers.V1.HelloWorldController>().HasApiVersion(new ApiVersion(1, 0)); }); |
Here we have now defined that the Controllers.V1.HelloWorldController have version 1.
STEP 3: CALL YOUR ENDPOINT
The endpoint will now respond to the following URL:
- /v1/helloworld
WHY NOT JUST HARDCODING THE API VERSION TO THE CONTROLLER ROUTE?
Versioning have several advantages. This is not all it can do:
You can deprecate versions by adding the following attribute to the controller:
|
1
2
3
|
[Route("v{version:apiVersion}/[controller]")][ApiVersion("1.0", Deprecated = true)]public class HelloWorldController : Controller |
You can map a specific method in a controller to a specific version by adding the following attribute to the method. So one controller can have several versions of an endpoint:
|
1
2
3
|
[HttpGet][MapToApiVersion("1.0")]public async Task<IActionResult> HelloWorld() |
And you can do a whole lot of other version related stuff. But this will get you started.
Please note that versioning is not supported when using .NET 6 Miminal API’s, but there is a plan to implement it later.
You are now an API versioning expert. Happy coding.
MORE TO READ:
- How to use API versioning in ASP.NET Core from InfoWorld
- .NET 6.0 and Simple (minimal) Api’s: Create an Api without controllers from briancaos
- API Versioning in ASP.NET Core from CodeMaze

浙公网安备 33010602011771号