Web Api如何在Swagger中为所有API添加标头参数 [英] Web Api How to add a Header parameter for all API in Swagger
问题描述
我搜索了添加请求标头参数的可能方法,该参数将自动添加到我的web-api
中的每个方法中,但是我找不到一个清晰的方法.
I searched for possible ways to add a request header parameter that would be added automatically to every method in my web-api
but i couldn't find a clear one.
在搜索时,我发现方法OperationFilter()
必须对此做一些事情.
While searching i found that the method OperationFilter()
has to do something about it.
推荐答案
是的,您可以通过继承IOperationFilter
Yes you can do it via inheriting from IOperationFilter
您可以在GitHub上找到答案: AddRequiredHeaderParameter >
You can find the answer on GitHub here: AddRequiredHeaderParameter
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "X-User-Token",
In = "header",
Type = "string",
Required = false
});
}
}
然后转到SwaggerConfig.cs
文件,并在AddSwaggerGen
部分中添加以下内容:
Then you go to your SwaggerConfig.cs
file and add the following in the AddSwaggerGen
section:
c.OperationFilter<AddRequiredHeaderParameter>();
重建并享受.
这篇关于Web Api如何在Swagger中为所有API添加标头参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!