How to send Authorization header with a request in Swagger UI?

后端 未结 4 1032
孤独总比滥情好
孤独总比滥情好 2020-12-31 02:33

I have a ASP.NET Web Api 2 application. I added Swashbuckle to it (Swagger for .NET). It displays my endpoints no problem, but in order to send a request I need to attach an

4条回答
  •  误落风尘
    2020-12-31 03:13

    I think it's not a good way to send the authorization header by modifying index.html. You can only add some settings to achieve that.
    Here is my solution:
    1.Add settings in Starup.cs ConfigureServices method

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(config => {
                config.SwaggerDoc("v1", new OpenApiInfo() { Title = "WebAPI", Version = "v1" });
                config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                config.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        Array.Empty()
                    }
                });
            });
        }
    

    2.Add settings in Startup.cs Configure method

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Document"));
        }
    

    After add settings, then run this project, you can find an Authorization button swagger page, and you can use it to set the authorization header.

提交回复
热议问题