MultipleApiVersions with Swagger

喜夏-厌秋 提交于 2019-12-12 18:07:26

问题


I am trying to enable versioning on a REST API, where the version is specified in the header, as "api-version":2, vendor media type, as "accept: application/vnd.company.resource-v2+json, application/json; version=2", or in a query string "?version=2". The implementation is using IHttpRouteConstraint and RouteFactoryAttribute. This works perfectly. However, Swagger is not able match the right model with the correct versioned document. The operationId is always from the version 1 model.

public class DevicesController : ApiController
{
    [HttpGet, RouteVersion( "api/devices", 1, Name = "v1.devices" )]
    [ResponseType( typeof( IEnumerable<Models.V1.Device> ) )]
    public IHttpActionResult GetV1( )
    {
        return Ok( new List<Models.V1.Device> { ... } );
    }

    [HttpGet, RouteVersion( "api/devices", 2, Name = "v2.devices" )]
    [ResponseType( typeof( IEnumerable<Models.V2.Device> ) )]
    public IHttpActionResult GetV2( )
    {
        return Ok( new List<Models.V2.Device> { ... } );
    }
}

Swagger docs for V2 has the wrong operationId and MIME Types.

"tags":
[
    "Devices"
],
"summary": "Get a list of device(s) by the device identifier",
"operationId": "Devices_GetV1",
"consumes": [ ],
"produces": 
[
    "application/vnd.safe.inventory-v1+json",
    "application/json",
    "text/json",
    "application/vnd.safe.inventory-v1+xml",
    "application/xml",
    "text/xml"
],
...

Swashbuckle 5.2.2

I have tried customizing the ApiExplorer as descripted in these post:

github.com/domaindrivendev/Swashbuckle/issues/558
github.com/domaindrivendev/Swashbuckle/issues/317

I have also tried building a custom selector.

I also went down this route as well, but I don’t think that is the same issue. https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

Asking for any direction any help would be appreciated.

Thanks in advance.


回答1:


Try add Microsoft.AspNet.WebApi.Versioning.ApiExplorer and use apiExplorer as explained here: https://github.com/Microsoft/aspnet-api-versioning/wiki/API-Documentation This works for me.




回答2:


We figured out a solution with a custom ApiExplorer as described in http://blog.ulriksen.net/versioned-iapiexplorer

In the Swagger configuration: using MultipleApiVersions

c.MultipleApiVersions( ( apiDesc, version ) =>
{
    var versionConstraint = apiDesc.Route.Constraints[ "version" ] as RouteVersionConstraint;
    return ( versionConstraint != null ) && versionConstraint.AllowedVersion == version.ConvertTo<int>( );
},
vc =>
{
    vc.Version( "2", "API V2" ); //add this line when v2 is released
    vc.Version( "1", "API V1" );
} );


来源:https://stackoverflow.com/questions/34823154/multipleapiversions-with-swagger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!