Swashbuckle使所有路由参数对于具有相同动词但在asp.net core 3.1 api swagger ui中具有多个路由的终结点都是强制性的

问题描述 投票:0回答:1

我正在研究asp.net core 2.2项目,并升级到asp.net core 3.1,还将Swashbuckle.AspNetCore升级到5.0.0。升级后,我可以看到所有更改产生的端点。

我有一个[HttpDelete]的端点,有两个不同的路由,如下所示:

[HttpDelete("{id}")]
[HttpDelete("{id}/some/{anotherId}")]
public IActionResult Delete(int id, int anotherId) 
{
    return NoContent();
}

[HttpDelete("{id}")]

此处仅需要id参数。但是idanotherId参数在此也都标记为必需。 这是错误的

enter image description here

[HttpDelete("{id}/some/{anotherId}")]

idanotherId都应在此处输入。 这是正确的。

enter image description here

这里是我的Startup.cs

ConfigureServices:

services.AddVersionedApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VV";
});

services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
    options.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
});

var apiVersionDescriptionProvider =
    services.BuildServiceProvider().GetService<IApiVersionDescriptionProvider>();

services
    .AddSwaggerGen(options =>
{
    foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
    {
        options.SwaggerDoc(
            $"TestDocumentOpenAPISpecification{description.GroupName}",
            new Microsoft.OpenApi.Models.OpenApiInfo
            {
                Title = "Test Document API",
                Version = description.ApiVersion.ToString(),
                Description = "Test",
                Contact = new Microsoft.OpenApi.Models.OpenApiContact
                {
                    Email = "[email protected]",
                    Name = "Test Team",
                    Url = new Uri("https://www.test.com")
                }
            });
    }

    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Input your JWT Authorization header to access this API. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] { }
        }
    });

    options.DocInclusionPredicate((documentName, apiDescription) =>
    {
        var actionApiVersionModel = apiDescription.ActionDescriptor
        .GetApiVersionModel(ApiVersionMapping.Explicit | ApiVersionMapping.Implicit);

        if (actionApiVersionModel == null)
        {
            return true;
        }

        if (actionApiVersionModel.DeclaredApiVersions.Any())
        {
            return actionApiVersionModel.DeclaredApiVersions.Any(v =>
            $"TestDocumentOpenAPISpecificationv{v.ToString()}" == documentName);
        }

        return actionApiVersionModel.ImplementedApiVersions.Any(v =>
            $"TestDocumentOpenAPISpecificationv{v.ToString()}" == documentName);
    });

    //var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    //var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

    //options.IncludeXmlComments(xmlCommentsFullPath);
});

配置:

app.UseSwagger();

app.UseSwaggerUI(options =>
{
    foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
    {
        options.SwaggerEndpoint(
            $"/swagger/TestDocumentOpenAPISpecification{description.GroupName}/swagger.json",
            $"Test Document API - {description.GroupName.ToUpperInvariant()}");
    }
    options.RoutePrefix = string.Empty;

    options.DefaultModelExpandDepth(2);
    options.DefaultModelRendering(Swashbuckle.AspNetCore.SwaggerUI.ModelRendering.Model);
    options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
    options.DisplayRequestDuration();
    options.EnableValidator();
    options.EnableFilter();
    options.EnableDeepLinking();
    options.DisplayOperationId();
});

产生的摇摇欲坠使anotherId在两条路径中都是必选的。以前不是那样的。我尝试将Name添加到两个路由,但仍然失败。请协助解决我的错。

swagger swagger-ui swashbuckle asp.net-core-3.1 swashbuckle.aspnetcore
1个回答
0
投票

经过一些分析,我已经使用IOperationFilter使它起作用。

public class DeleteOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.HttpMethod == "DELETE" && context.MethodInfo.Name == "Delete")
        {
            foreach (var parameter in context.ApiDescription.ParameterDescriptions)
            {
                if (parameter.RouteInfo == null)
                {
                    operation.Parameters.Single(x => x.Name.Equals(parameter.Name)).Required = false;
                }
            }
            return;
        }
    }
}

并将其添加到ConfigureServices中,

services.AddSwaggerGen(options =>
{
    ...
    options.OperationFilter<DeleteOperationFilter>();
};

不确定这是最好的方法,但是可以。如果我错了,请纠正我。

© www.soinside.com 2019 - 2024. All rights reserved.