我正在尝试使用Swashbuckle为我们的API设置Swagger。我们的每个控制器都继承自具有约8个参数(userId,语言,平台等)的BaseController。它们每个都具有只读变量,其get函数设置为从引入的标头中读取值。例如:
protected int UserID
{
get
{
return int.Parse(HttpContext.Current.Request.Headers["user_Id"]);
}
}
当我第一次安装Swagger时,它只会提供传递方法中列出的参数的选项。这些参数始终不包括在BaseController中设置的〜8参数,因此,如果控制器使用用户ID,则方法签名中不会列出用户ID。作为用户ID,不会显示在Swagger生成的UI中。
现在,我一直在尝试使用SwaggerOperation属性,如下所示:
[SwaggerOperation("UserValidate(UserID)")]
public int UserValidate()
{
return this._UserValidateService.UserValidate(this.UserID);
而且我有一个自定义的swagger参数,它检查所有方法的SwaggerOperation名称是否包含“ UserID”,如果是,则将UserID标头添加到该调用中。
我的问题是,我必须手动处理每个调用并添加swagger操作,如果调用发生更改,我们必须记住还要更改SwaggerOperation。
[我还考虑过仅将8添加到每个API调用中并将它们标记为可选,但这听起来会使UI膨胀得很厉害。
请告知情况。我有没有考虑过的选择?它们是我错过的Swashbuckle功能,可以解决我的问题吗?
提前感谢。
如果使用swashbuckle> = 5,则可以如下添加操作过滤器。它将仅向选定的请求添加标头:
public class AddHeaderParameter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.ApiDescription.HttpMethod.Equals("POST") && context.ApiDescription.RelativePath.Contains("login"))
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter
{
Name = "UserId",
In = ParameterLocation.Header,
Schema = new OpenApiSchema
{
Type = "String",
},
Required = true
});
}
}
上面添加了必需的标头,只有带有操作名称作为登录名的POST操作。