How can versioning be done in ASP.NET Core Web Api

后端 未结 4 1665
耶瑟儿~
耶瑟儿~ 2020-12-25 09:10

In previous asp.net web api, I implement DefaultHttpControllerSelector to specify how I want the request to locate my controller. I often have diff

4条回答
  •  滥情空心
    2020-12-25 09:38

    For that Add service API versioning to your ASP.NET Core applications

      public void ConfigureServices( IServiceCollection services )
        {
            services.AddMvc();
            services.AddApiVersioning();
    
            // remaining other stuff omitted for brevity
        }
    

    QUERYSTRING PARAMETER VERSIONING

    [ApiVersion( "2.0" )]
    [Route( "api/helloworld" )]
    public class HelloWorld2Controller : Controller {
        [HttpGet]
        public string Get() => "Hello world!";
    }
    

    So this means to get 2.0 over 1.0 in another Controller with the same route, you'd go here:

    /api/helloworld?api-version=2.0

    we can have the same controller name with different namespaces

    URL PATH SEGMENT VERSIONING

     [ApiVersion( "1.0" )]
     [Route( "api/v{version:apiVersion}/[controller]" )]
     public class HelloWorldController : Controller {
        public string Get() => "Hello world!";
     }
    [ApiVersion( "2.0" )]
    [ApiVersion( "3.0" )]
    [Route( "api/v{version:apiVersion}/helloworld" )]
    public class HelloWorld2Controller : Controller {
        [HttpGet]
        public string Get() => "Hello world v2!";
    
        [HttpGet, MapToApiVersion( "3.0" )]
        public string GetV3() => "Hello world v3!";
    }
    

    Header Versioning

      public void ConfigureServices( IServiceCollection services )
        {
            services.AddMvc();
            services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
        }
    

    When you do HeaderApiVersioning you won't be able to just do a GET in your browser, so I'll use Postman to add the header (or I could use Curl, or WGet, or PowerShell, or a Unit Test):

    Image

    please refer https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

提交回复
热议问题