美文网首页
Web Api 2.0中使用Swagger生成Api文档的2个小

Web Api 2.0中使用Swagger生成Api文档的2个小

作者: 创新科技宝典 | 来源:发表于2017-08-05 13:04 被阅读0次

…本

当Web Api 2.0使用OAuth2授权时,如何在Swagger中添加Authorization请求头?

Swagger说明文档支持手动调用Api, 但是当Api使用OAuth2授权时,由于没有地方可以输入授权Token, 导致响应结果一直是401没有授权。

解决方案:

在Swagger配置文件中,添加对请求头中Authorization的设置。

1. 在Api项目中添加一个新类AddAuthorizationHeader并实现IOperationFilter接口

publicclassAddAuthorizationHeader : IOperationFilter

{//////Adds an authorization header to the given operation in Swagger.//////The Swashbuckle operation.///The Swashbuckle schema registry.///The Swashbuckle api description.publicvoidApply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)

{if(operation ==null)return;if(operation.parameters ==null)

{

operation.parameters=newList();

}varparameter =newParameter

{

description="Token",

@in="header",

name="Authorization",

required=true,

type="string"};if(apiDescription.ActionDescriptor.GetCustomAttributes().Any())

{//如果Api方法是允许匿名方法,Token不是必填的parameter.required=false;

}

operation.parameters.Add(parameter);

}

}

2. 在SwaggerConfig.cs中启用Authorization请求头。

publicstaticvoidRegister(HttpConfiguration config)

{varthisAssembly =typeof(SwaggerConfig).Assembly;

config.EnableSwagger(c=>{

相关文章

网友评论

      本文标题:Web Api 2.0中使用Swagger生成Api文档的2个小

      本文链接:https://www.haomeiwen.com/subject/ixwilxtx.html