Web Api How to add a Header parameter for all API in Swagger

后端 未结 7 933
温柔的废话
温柔的废话 2020-11-27 16:54

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.

相关标签:
7条回答
  • 2020-11-27 17:16

    What the user "G T" wrote is correct but it is not working with Swagger 5. We have some new changes:

    From: Operation to: OpenApiOperation

    From: IParameter to: OpenApiParameter

    From: NonBodyParameter to: OpenApiParameter, and the most important is...

    From: Type = "string" to: Schema = new OpenApiSchema { Type = "String" }

    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.OpenApi.Any;
    using Microsoft.OpenApi.Models;
    using Swashbuckle.AspNetCore.SwaggerGen;
    namespace MyAPI
    {
        public class AuthorizationHeaderParameterOperationFilter: IOperationFilter
        {
            public void Apply(OpenApiOperation operation, OperationFilterContext context)
            {
                var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
                var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
                var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
    
                if (isAuthorized && !allowAnonymous)
                {
                    if (operation.Parameters == null)
                        operation.Parameters = new List<OpenApiParameter>();
    
                    operation.Parameters.Add(new OpenApiParameter 
                    {
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Description = "access token",
                        Required = true,
                        Schema = new OpenApiSchema
                        {
                            Type = "String",
                            Default = new OpenApiString("Bearer ")
                        }
                    });
                }
            }
        }
    }
    

    And in Startup => ConfigureServices => services.AddSwaggerGen()

    c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
    
    0 讨论(0)
提交回复
热议问题