.net core Swagger添加bearer token参数

引入swagger后,在services.AddSwaggerGen中增加如下内容
//Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{

            //Bearer 的scheme定义
            var securityScheme = new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                //参数添加在头部
                In = ParameterLocation.Header,
                //使用Authorize头部
                Type = SecuritySchemeType.Http,
                //内容为以 bearer开头
                Scheme = "bearer",
                BearerFormat = "JWT"
            };

            //把所有方法配置为增加bearer头部信息
            var securityRequirement = new OpenApiSecurityRequirement
                {
                    {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "bearerAuth"
                                }
                            },
                            new string[] {}
                    }
                };

            //注册到swagger中
            c.AddSecurityDefinition("bearerAuth", securityScheme);
            c.AddSecurityRequirement(securityRequirement);
        });
        添加成功后,swagger右上方会有一个Authroize按钮,点击后可以输入bearer token。

.net core Swagger添加bearer token参数_第1张图片
每个API方法后,会有一个锁的标志,表明该方法会传递bearer token。在这里插入图片描述
转载于 https://www.cnblogs.com/mosakashaka/p/13151629.html

你可能感兴趣的:(NetCore,c#)