您好,登錄后才能下訂單哦!
如何在.Net Core Api中使用版本控制?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
1,安裝Microsoft.AspNetCore.Mvc.Versioning
NET Core Mvc中,微軟官方提供了一個(gè)可用的Api版本控制庫Microsoft.AspNetCore.Mvc.Versioning。
2,修改Startup類
這里我們需要在Startup類的ConfigureService方法中添加以下代碼。
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddApiVersioning(o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); //o.ApiVersionReader = new HeaderApiVersionReader("x-api-version"); }); }
3,代碼
//版本1控制器 [ApiVersion("1.0", Deprecated = true)] [Route("api/values")] [ApiController] public class ValuesV1Controller : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new string[] { "這是版本1.0返回的——數(shù)據(jù)1", "這是版本1.0返回的——數(shù)據(jù)2" }; } }
//版本2控制器 [ApiVersion("2.0")] [Route("api/values")] [ApiController] public class ValuesV2Controller : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new string[] { "這是版本2.0返回的——數(shù)據(jù)1", "這是版本2.0返回的——數(shù)據(jù)2" }; } }
關(guān)于如何在.Net Core Api中使用版本控制問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。