swagger ui 怎么输入对象_api-如何在Swagger UI中发送带有请求的自定义标头?

这篇博客讨论了如何在Swagger UI中为API请求添加自定义的Authorization标头。作者提到了几种方法,包括在ASP.NET WebApi中使用IOperationFilter接口,通过Swagger的securityDefinitions和security要求,以及在ASP.NET Core中使用Swashbuckle.AspNetCore添加安全定义。这些方法允许用户在Swagger UI中输入和管理请求标头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

api-如何在Swagger UI中发送带有请求的自定义标头?

我在API中有一些终结点-Authorization、/products。

在Swagger用户界面中,我将Authorization和/products发布到/user/login,作为响应,我收到了token字符串。

然后,我可以从响应中复制令牌,并希望将其用作请求中所有URL的请求中的Authorization标头值,并作为示例使用到/products。

我应该在Swagger UI页面上的某个位置手动创建文本输入,然后将令牌放在那里并以某种方式注入请求中,还是有工具以更好的方式对其进行管理?

9个解决方案

47 votes

在ASP.net WebApi中,在Swagger UI上传递标头的最简单方法是在IOperationFilter接口上实现2700743447908908184184方法。

将此添加到您的项目:

public class AddRequiredHeaderParameter : IOperationFilter

{

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)

{

if (operation.parameters == null)

operation.parameters = new List();

operation.parameters.Add(new Parameter

{

name = "MyHeaderField",

@in = "header",

type = "string",

description = "My header field",

required = true

});

}

}

在SwaggerConfig.cs中,使用c.OperationFilter<>()从上方注册过滤器:

public static void Register()

{

var thisAssembly = typeof(SwaggerConfig).Assembly;

GlobalConfiguration.Configuration

.EnableSwagger(c =>

{

c.SingleApiVersion("v1", "YourProjectName");

c.IgnoreObsoleteActions();

c.UseFullTypeNameInSchemaIds();

c.DescribeAllEnumsAsStrings();

c.IncludeXmlComments(GetXmlCommentsPath());

c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

c.OperationFilter(); // Add this here

})

.EnableSwaggerUi(c =>

{

c.DocExpansion(DocExpansion.List);

});

}

ShaTin answered 2020-01-13T11:22:47Z

38 votes

您可以在请求中添加标头参数,而Swagger-UI会将其显示为可编辑文本框:

swagger: "2.0"

info:

version: 1.0.0

title: TaxBlaster

host: taxblaster.com

basePath: /api

schemes:

- http

paths:

/taxFilings/{id}:

get:

parameters:

- name: id

in: path

description: ID of the requested TaxFiling

required: true

type: string

- name: auth

in: header

description: an authorization header

required: true

type: string

responses:

200:

description: Successful response, with a representation of the Tax Filing.

schema:

$ref: "#/definitions/TaxFilingObject"

404:

description: The requested tax filing was not found.

definitions:

TaxFilingObject:

type: object

description: An individual Tax Filing record.

properties:

filingID:

type: string

year:

type: string

period:

type: integer

currency:

type: string

taxpayer:

type: object

您还可以使用security类型添加安全定义:

swagger: "2.0"

info:

version: 1.0.0

title: TaxBlaster

host: taxblaster.com

basePath: /api

schemes:

- http

securityDefinitions:

api_key:

type: apiKey

name: api_key

in: header

description: Requests should pass an api_key header.

security:

- api_key: []

paths:

/taxFilings/{id}:

get:

parameters:

- name: id

in: path

description: ID of the requested TaxFiling

required: true

type: string

responses:

200:

description: Successful response, with a representation of the Tax Filing.

schema:

$ref: "#/definitions/TaxFilingObject"

404:

description: The requested tax filing was not found.

definitions:

TaxFilingObject:

type: object

description: An individual Tax Filing record.

properties:

filingID:

type: string

year:

type: string

period:

type: integer

currency:

type: string

taxpayer:

type: object

security对象定义了安全方案。

2700742799888888221184对象(在Swagger–OpenAPI中称为“安全要求”)将安全方案应用于给定的上下文。 在我们的案例中,我们通过将安全性要求声明为顶级来将其应用于整个API。 我们可以选择在各个路径项和/或方法中覆盖它。

这将是指定您的安全方案的首选方法。 并替换第一个示例中的header参数。 不幸的是,Swagger-UI至少在到目前为止的测试中没有提供文本框来控制此参数。

Ted Epstein answered 2020-01-13T11:22:18Z

19 votes

在ASP.NET Core 2 Web API中,使用Swashbuckle.AspNetCore软件包2.1.0,实现IDocumentFilter:

SwaggerSecurityRequirementsDocumentFilter.cs

using System.Collections.Generic;

using Swashbuckle.AspNetCore.Swagger;

using Swashbuckle.AspNetCore.SwaggerGen;

namespace api.infrastructure.filters

{

public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter

{

public void Apply(SwaggerDocument document, DocumentFilterContext context)

{

document.Security = new List>>()

{

new Dictionary>()

{

{ "Bearer", new string[]{ } },

{ "Basic", new string[]{ } },

}

};

}

}

}

在Startup.cs中,配置安全定义并注册自定义过滤器:

public void ConfigureServices(IServiceCollection services)

{

services.AddSwaggerGen(c =>

{

// c.SwaggerDoc(.....

c.AddSecurityDefinition("Bearer", new ApiKeyScheme()

{

Description = "Authorization header using the Bearer scheme",

Name = "Authorization",

In = "header"

});

c.DocumentFilter();

});

}

在Swagger UI中,单击“授权”按钮并设置令牌的值。

结果:

curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"

gpaoli answered 2020-01-13T11:23:25Z

3 votes

也可以将[FromHeader]属性用于应在自定义标头中发送的网络方法参数(或Model类中的属性)。 像这样:

[HttpGet]

public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)

至少它对于ASP.NET Core 2.1和Swashbuckle.AspNetCore 2.5.0正常工作。

Victor Sharovatov answered 2020-01-13T11:23:49Z

2 votes

这是ASP.NET Core Web Api / Swashbuckle组合的简单答案,不需要您注册任何自定义过滤器。 你知道第三次是魅力:)。

将以下代码添加到Swagger配置中,将显示“授权”按钮,使您可以输入要为所有请求发送的承载令牌。 询问时,请不要忘记输入此令牌作为Bearer 。

请注意,以下代码将为所有请求和操作发送令牌,这可能是您想要的,也可能不是您想要的。

services.AddSwaggerGen(c =>

{

//...

c.AddSecurityDefinition("Bearer", new ApiKeyScheme()

{

Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",

Name = "Authorization",

In = "header",

Type = "apiKey"

});

c.AddSecurityRequirement(new Dictionary>

{

{ "Bearer", new string[] { } }

});

//...

}

通过这个线程。

Vlad Iliescu answered 2020-01-13T11:24:23Z

1 votes

对于那些使用NSwag并需要自定义标头的用户:

app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>

{

settings.GeneratorSettings.IsAspNetCore = true;

settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));

settings.GeneratorSettings.DocumentProcessors.Add(

new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme

{

Type = SwaggerSecuritySchemeType.ApiKey,

Name = "header-name",

Description = "header description",

In = SwaggerSecurityApiKeyLocation.Header

}));

});

}

Swagger用户界面将包含一个“授权”按钮。

Ofiris answered 2020-01-13T11:24:47Z

0 votes

我到这里结束是因为我试图根据我添加到API方法中的我自己的apiDescription属性在Swagger UI中有条件地添加标头参数。 根据@Corcus在评论中列出的提示,我能够得出自己的解决方案,并希望它将对其他人有所帮助。

使用反射,它将检查嵌套在apiDescription中的方法是否具有所需的属性(在我的情况下为MyApiKeyAuthenticationAttribute)。 如果是这样,我可以附加所需的标题参数。

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {

if (operation.parameters == null)

operation.parameters = new List();

var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)

((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo

.GetCustomAttributes(false);

if(attributes != null && attributes.Any()) {

if(attributes.Where(x => x.GetType()

== typeof(MyApiKeyAuthenticationAttribute)).Any()) {

operation.parameters.Add(new Parameter {

name = "MyApiKey",

@in = "header",

type = "string",

description = "My API Key",

required = true

});

operation.parameters.Add(new Parameter {

name = "EID",

@in = "header",

type = "string",

description = "Employee ID",

required = true

});

}

}

}

InbetweenWeekends answered 2020-01-13T11:25:13Z

0 votes

免责声明:此解决方案未使用Header。

如果有人正在寻找一种懒惰-懒惰的方式(同样在WebApi中),我建议:

public YourResult Authorize([FromBody]BasicAuthCredentials credentials)

您不是从标题中获取信息,但是至少您有一个简单的选择。您始终可以检查对象是否为null并回退到标头机制。

Cesar answered 2020-01-13T11:25:46Z

0 votes

Golang / go-swagger示例:[https://github.com/go-swagger/go-swagger/issues/1416]

// swagger:parameters opid

type XRequestIdHeader struct {

// in: header

// required: true

XRequestId string `json:"X-Request-Id"`

}

...

// swagger:operation POST /endpoint/ opid

// Parameters:

// - $ref: #/parameters/XRequestIDHeader

Qiang Li answered 2020-01-13T11:26:06Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值