Web Api 如何在 Swagger 中为所有 API 添加 Header 参数 [英] Web Api How to add a Header parameter for all API in Swagger

查看:92
本文介绍了Web Api 如何在 Swagger 中为所有 API 添加 Header 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了添加请求标头参数的可能方法,该参数会自动添加到我的 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.

推荐答案

是的,你可以通过继承 IOOperationFilter

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 添加 Header 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆