问题描述
我目前正在使用 Swagger Ui 开发 WebApi。我正面临一个奇怪的问题。当用户尝试调用 API 时,我将一些标题字段设置为强制(*必需)字段。
如果用户错过传递任何标题,它假设显示图像1中给出的警告。(在图像1中,红色标记的字段是查询参数)它工作正常但不适用于标题。
对于标题,我遇到了如图 2 所示的问题。错误假设出现在 UI 上,但它出现在浏览器控制台窗口中。
IOOperationFilter 中的代码如下
public void Apply(OpenApiOperation operation,OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-Transaction-Id",In = ParameterLocation.Header,required = true,AllowEmptyValue=false,Description="Transaction Id to track the issue"
});
}
注意:- 我已经使用 IOperationFilter
来设置所需的标头。使用 Swashbuckle.AspNetCore(5.6.3)
。对此的任何帮助都会非常棒!
解决方法
您必须为标头参数指定Schema
(数据类型),例如:
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-Transaction-Id",...
Schema = new OpenApiSchema // <-----------------
{
Type = "string"
}
});