ASP.NET Core WebApi版本控制的實(shí)現(xiàn)
前言:
在日常項(xiàng)目開(kāi)發(fā)中,隨著項(xiàng)目需求不斷的累加、不斷的迭代;項(xiàng)目服務(wù)接口需要向下兼容歷史版本;前些時(shí)候就因?yàn)锳pi接口為做版本管理導(dǎo)致接口對(duì)低版本兼容處理不友好。
最近就像了解下如何實(shí)現(xiàn)WebApi版本控制,那么版本控制有什么好處呢?
WebApi版本控制的好處
- 有助于及時(shí)推出功能, 而不會(huì)破壞現(xiàn)有系統(tǒng),兼容性處理更友好。
- 它還可以幫助為選定的客戶(hù)提供額外的功能。
接下來(lái)就來(lái)實(shí)現(xiàn)版本控制以及在Swagger UI中接入WebApi版本
一、WebApi版本控制實(shí)現(xiàn)
通過(guò)Microsoft.AspNetCore.Mvc.Versioning實(shí)現(xiàn)webapi 版本控制
創(chuàng)建WebApi項(xiàng)目,添加Nuget包:Microsoft.AspNetCore.Mvc.Versioning
Install-Package Microsoft.AspNetCore.Mvc.Versioning
修改項(xiàng)目Startup文件,使用Microsoft.AspNetCore.Mvc.Versioning
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //根據(jù)需要設(shè)置,以下內(nèi)容 services.AddApiVersioning(apiOtions => { //返回響應(yīng)標(biāo)頭中支持的版本信息 apiOtions.ReportApiVersions = true; //此選項(xiàng)將用于不提供版本的請(qǐng)求。默認(rèn)情況下, 假定的 API 版本為1.0 apiOtions.AssumeDefaultVersionWhenUnspecified = true; //缺省api版本號(hào),支持時(shí)間或數(shù)字版本號(hào) apiOtions.DefaultApiVersion = new ApiVersion(1, 0); //支持MediaType、Header、QueryString 設(shè)置版本號(hào);缺省為QueryString、UrlSegment設(shè)置版本號(hào);后面會(huì)詳細(xì)說(shuō)明對(duì)于作用 apiOtions.ApiVersionReader = ApiVersionReader.Combine( new MediaTypeApiVersionReader("api-version"), new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"), new UrlSegmentApiVersionReader()); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); //使用ApiVersioning app.UseApiVersioning(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
WebApi設(shè)置版本:
a)通過(guò)ApiVersion標(biāo)記指定指定控制器或方法的版本號(hào);Url參數(shù)控制版本(QueryStringApiVersionReader),如下:
namespace WebAPIVersionDemo.Controllers { [ApiController] [Route("[controller]")] //Deprecated=true:表示v1即將棄用,響應(yīng)頭中返回 [ApiVersion("1.0", Deprecated = true)] [ApiVersion("2.0")]public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"}; [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = $"v1:{Summaries[rng.Next(Summaries.Length)]}" }) .ToArray(); } } }
通過(guò)參數(shù)api-version參數(shù)指定版本號(hào);調(diào)用結(jié)果:
b)通過(guò)Url Path Segment控制版本號(hào)(UrlSegmentApiVersionReader):為控制器添加路由方式如下,apiVersion為固定格式
[Route("/api/v{version:apiVersion}/[controller]")]
調(diào)用方式:通過(guò)調(diào)用路徑傳入版本號(hào),如:http://localhost:5000/api/v1/weatherforecast
c)通過(guò)Header頭控制版本號(hào):在Startup中設(shè)置(HeaderApiVersionReader、MediaTypeApiVersionReader)
apiOtions.ApiVersionReader = ApiVersionReader.Combine( new MediaTypeApiVersionReader("api-version"), new HeaderApiVersionReader("api-version"));
調(diào)用方式,在請(qǐng)求頭或中MediaType中傳遞api版本,如下:
其他說(shuō)明:
a)ReportApiVersions設(shè)置為true時(shí), 返回當(dāng)前支持版本號(hào)(api-supported-versions);Deprecated 參數(shù)設(shè)置為true表示已棄用,在響應(yīng)頭中也有顯示(api-deprecated-versions):
b)MapToApiVersion標(biāo)記:允許將單個(gè)API操作映射到任何版本(可以在v1的控制器中添加v3的方法);在上面控制器中添加以下代碼,訪(fǎng)問(wèn)v3版本方法
[HttpGet] [MapToApiVersion("3.0")] public IEnumerable<WeatherForecast> GetV3() { //獲取版本 string v = HttpContext.GetRequestedApiVersion().ToString(); var rng = new Random(); return Enumerable.Range(1, 1).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = $"v{v}:{Summaries[rng.Next(Summaries.Length)]}" }) .ToArray(); }
c)注意事項(xiàng):
1、路徑中參數(shù)版本高于,其他方式設(shè)置版本
2、多種方式傳遞版本,只能采用一種方式傳遞版本號(hào)
3、SwaggerUI中MapToApiVersion設(shè)置版本不會(huì)單獨(dú)顯示
二、Swagger UI中版本接入
1、添加包:Swashbuckle.AspNetCore、Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
//swaggerui 包 Install-Package Swashbuckle.AspNetCore //api版本 Install-Package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
2、修改Startup代碼:
public class Startup { /// <summary> /// Api版本提者信息 /// </summary> private IApiVersionDescriptionProvider provider; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //根據(jù)需要設(shè)置,以下內(nèi)容 services.AddApiVersioning(apiOtions => { //返回響應(yīng)標(biāo)頭中支持的版本信息 apiOtions.ReportApiVersions = true; //此選項(xiàng)將用于不提供版本的請(qǐng)求。默認(rèn)情況下, 假定的 API 版本為1.0 apiOtions.AssumeDefaultVersionWhenUnspecified = true; //缺省api版本號(hào),支持時(shí)間或數(shù)字版本號(hào) apiOtions.DefaultApiVersion = new ApiVersion(1, 0); //支持MediaType、Header、QueryString 設(shè)置版本號(hào);缺省為QueryString設(shè)置版本號(hào) apiOtions.ApiVersionReader = ApiVersionReader.Combine( new MediaTypeApiVersionReader("api-version"), new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"), new UrlSegmentApiVersionReader()); }); services.AddVersionedApiExplorer(option => { option.GroupNameFormat = "接口:'v'VVV"; option.AssumeDefaultVersionWhenUnspecified = true; }); this.provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); services.AddSwaggerGen(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, new Microsoft.OpenApi.Models.OpenApiInfo() { Title = $"接口 v{description.ApiVersion}", Version = description.ApiVersion.ToString(), Description = "切換版本請(qǐng)點(diǎn)右上角版本切換" } ); } options.IncludeXmlComments(this.GetType().Assembly.Location.Replace(".dll", ".xml"), true); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //…… //使用ApiVersioning app.UseApiVersioning(); //啟用swaggerui,綁定api版本信息 app.UseSwagger(); app.UseSwaggerUI(c => { foreach (var description in provider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); //…… } }
3、運(yùn)行效果:
其他:
示例地址:https://github.com/cwsheng/WebAPIVersionDemo
到此這篇關(guān)于A(yíng)SP.NET Core WebApi版本控制的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)ASP.NET Core WebApi版本控制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
asp.net 使用駐留在頁(yè)面中的Cache緩存常用可定時(shí)更新的數(shù)據(jù)
這個(gè)就先需要先知道一下System.Web.Caching.Cache類(lèi),其實(shí)在我做WEB應(yīng)用的時(shí)候,我會(huì)將一些使用頻繁但是又要經(jīng)常使用并且需要急時(shí)更新的對(duì)象放到Cache中,這樣可以很大程序上減少?gòu)挠脖P(pán)上讀取數(shù)據(jù)的次數(shù)。2010-03-03ASP.NET MVC重寫(xiě)RazorViewEngine實(shí)現(xiàn)多主題切換
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC重寫(xiě)RazorViewEngine實(shí)現(xiàn)多主題切換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06深入.net調(diào)用webservice的總結(jié)分析
本篇文章是對(duì).net調(diào)用webservice進(jìn)行了詳細(xì)的總結(jié)與分析,需要的朋友參考下2013-05-05基于SignalR的消息推送與二維碼掃描登錄實(shí)現(xiàn)代碼
這篇文章主要介紹了基于SignalR的消息推送與二維碼掃描登錄實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-02-02如何在不同.net版本實(shí)現(xiàn)單點(diǎn)登錄
經(jīng)過(guò)研究,重寫(xiě)實(shí)現(xiàn)了一個(gè)可以在不同.net版本中實(shí)現(xiàn)單點(diǎn)登錄的簡(jiǎn)單方法?,F(xiàn)在和大家分享一下,不足之處還望見(jiàn)諒2013-07-07ASP.net與SQLite數(shù)據(jù)庫(kù)通過(guò)js和ashx交互(連接和操作)
這篇文章主要介紹了ASP.net與SQLite數(shù)據(jù)庫(kù)通過(guò)js和ashx交互(連接和操作),具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01asp.net使用Repeater控件中的全選進(jìn)行批量操作實(shí)例
這篇文章主要介紹了asp.net使用Repeater控件中的全選進(jìn)行批量操作方法,實(shí)例分析了Repeater控件的使用技巧,需要的朋友可以參考下2015-01-01如何利用擴(kuò)展方法來(lái)鏈?zhǔn)降膶?duì)MVC 3中的頁(yè)面進(jìn)行驗(yàn)證
雖然擴(kuò)展方法只是改變了我們寫(xiě)代碼的方式,但是如果我們使用得當(dāng),可以給我們帶來(lái)巨大的編碼效率的提升接下來(lái)介紹通過(guò)擴(kuò)展方法(鏈?zhǔn)椒椒ǎ镸VC 3視圖添加驗(yàn)證2013-01-01GridView自動(dòng)增加序號(hào)(三種實(shí)現(xiàn)方式)
第一種方式,直接在A(yíng)spx頁(yè)面GridView模板列中.這種的缺點(diǎn)是到第二頁(yè)分頁(yè)時(shí)又重新開(kāi)始了,第二種方式分頁(yè)時(shí)進(jìn)行了計(jì)算,這樣會(huì)累計(jì)向下加,點(diǎn)三種放在cs代碼中2013-04-04