如何在.Net Core Api中使用版本控制?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1,安裝Microsoft.AspNetCore.Mvc.Versioning
NET Core Mvc中,微軟官方提供了一個可用的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返回的——數據1", "這是版本1.0返回的——數據2" };
}
}//版本2控制器
[ApiVersion("2.0")]
[Route("api/values")]
[ApiController]
public class ValuesV2Controller : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "這是版本2.0返回的——數據1", "這是版本2.0返回的——數據2" };
}
}關于如何在.Net Core Api中使用版本控制問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。