0

我正在开发asp.net core 2.2项目并升级到asp.net core 3.1并升级Swashbuckle.AspNetCore5.0.0. 升级后,我可以看到 swagger 生成的端点发生了变化。

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

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

[HttpDelete("{id}")]

id这里应该只需要参数。但是这里idanotherId参数也被标记为必需。这是错误的

在此处输入图像描述

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

id和参数在这里都anotherId应该是必需的。这是对的。

在此处输入图像描述

这是我的Startup.cs

配置服务:

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 = "Test@test.com",
                    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到两条路线,但仍然失败。请协助我错在哪里。

4

1 回答 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>();
};

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

于 2020-03-17T07:10:23.397 回答