我正在研究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
参数。但是id
和anotherId
参数在此也都标记为必需。 这是错误的。
[HttpDelete("{id}/some/{anotherId}")]
id
和anotherId
都应在此处输入。 这是正确的。
这里是我的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
添加到两个路由,但仍然失败。请协助解决我的错。
经过一些分析,我已经使用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>();
};
不确定这是最好的方法,但是可以。如果我错了,请纠正我。