我已通过创建自定义属性 [ApiControllerParameter] 和 OperationFilter ApiControllerParameterFilter 来解决此问题,以修复生成的 Swagger 文档。
该属性采用string 参数,但您可以调整代码以满足您的需要。
用法:
[ApiController]
[Route("projects/{ownerName}/{projectName}")]
[ApiControllerParameter(name: "ownerName", example: "some-user", description: "name of user owning the project")]
[ApiControllerParameter(name: "projectName", example: "some-project")]
public class ProjectsController : ControllerBase {
// ...
}
// Startup.cs
services.AddSwaggerGen(options => {
options.SwaggerDoc("MyApplication", new OpenApiInfo {Title = "MyApplication", Version = "v1"});
// Add the filter to your swagger configuration
options.OperationFilter<SwaggerControllerParameterFilter>();
});
ApiControllerParameterAttribute:
using System;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ApiControllerParameterAttribute : SwaggerParameterAttribute
{
public readonly OpenApiParameter Parameter;
public ApiControllerParameterAttribute(
string name = null,
string description = null,
string example = null,
bool required = true
) : base(description)
{
this.Parameter = new OpenApiParameter {
Name = name,
In = ParameterLocation.Path,
Description = description,
Required = required,
Schema = new OpenApiSchema {
Type = "string",
Example = new OpenApiString(example)
},
};
}
}
SwaggerControllerParameterFilter:
using System;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
public class SwaggerControllerParameterFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.MethodInfo.DeclaringType is null) return;
var attributes = Attribute.GetCustomAttributes(context.MethodInfo.DeclaringType,
typeof(ApiControllerParameterAttribute))
.Cast<ApiControllerParameterAttribute>();
foreach (var attribute in attributes) {
var previousParameter = operation.Parameters.First(p => p.Name == attribute.Parameter.Name);
operation.Parameters.Remove(previousParameter);
operation.Parameters.Add(attribute.Parameter);
}
}
}