swagger 如何将头参数添加到API.NET Web API的特定控制器/方法

6ss1mwsb  于 2022-11-06  发布在  .NET
关注(0)|答案(2)|浏览(123)

我知道我可以在swagger中为所有API添加头参数,如Web Api How to add a Header parameter for all API in Swagger中所述
使用这种方法,header参数将显示在所有API的swagger UI中。
但不是所有的API/控制器都需要header参数,有没有办法只为特定的控制器甚至特定的API添加header?

cygmwpex

cygmwpex1#

虽然这篇文章是旧的,我认为它会帮助新来者,如果他们陷入同样的情况。

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry,
                      ApiDescription apiDescription)
    {
        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }

       /*System.Diagnostics.Trace.WriteLine(apiDescription.RelativePath +
          "=paath");*/
        if (apiDescription.RelativePath.Contains(***{url***}))
        {
            operation.parameters.Add(new Parameter
            {
                name = "X-User-Token",
                @in = "header",
                type = "string",
                required = false,
                description=""
            });
            operation.parameters.Add(new Parameter
            {
                name = "authorization",
                @in = "header",
                description = "Token",
                type = "string",
                required = true
            });
        }
        else
        {
            operation.parameters.Add(new Parameter
            {
                name = "X-User-Token",
                @in = "header",
                type = "string",
                required = false,
                description="description"
            });
        }
    }
}
wribegjk

wribegjk2#

在Asp.Net核心/. net 6中

using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;

namespace YourProduct
{
    public class HttpHeaderOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "X-your-Custom-header",
                In = ParameterLocation.Header,
                AllowEmptyValue = true,
                Required = false,
                Description = "Your custom header Name"

            });
        }
    }
}

在行动中

[HttpPost("[action]")]
[SwaggerOperationFilter(typeof(HttpHeaderOperationFilter))] //<-- point of interest
public IActionResult DoSomething([FromBody] YourModel model)
{
. . . . . . .

别忘了startup.cs

services.AddSwaggerGen(opt =>
{
    opt.EnableAnnotations(); // <-- this
}

相关问题