NSwag给api加上说明
给controller加上description
https://github.com/RSuter/NSwag/issues/1803
xml summary
https://github.com/RSuter/NJsonSchema/wiki/XML-Documentation
WebApiToSwaggerGenerator
- Package: NSwag.SwaggerGeneration.WebApi,NSwag.Annotations
- Settings: WebApiToSwaggerGeneratorSettings
- Usage: Code (below)
The WebApiToSwaggerGenerator
class is used to generate a Swagger specification from ASP.NET Web API controllers:
下面这一块的代码的使用,参看Serve the Swagger specification from a Web API action部分的第二节
var settings = new WebApiToSwaggerGeneratorSettings
{
DefaultUrlTemplate = "api/{controller}/{action}/{id}"
};
var generator = new WebApiToSwaggerGenerator(settings);
var document = await generator.GenerateForControllerAsync<PersonsController>();
var swaggerSpecification = document.ToJson();
The generator internally uses the JsonSchemaGenerator class (NJsonSchema project) to generate the JSON Schemas of the request and response DTO types.
To generate the Swagger specification for Web API controllers in an external .NET assembly, use the WebApiAssemblyToSwaggerGenerator class.
ASP.NET Core
Important: This reflection based generator will eventually be deprecated by the new APi Explorer based generator AspNetCoreToSwaggerGenerator!
When generating a Swagger specification for an ASP.NET Core application, set the IsAspNetCore
setting to true.
Supported ASP.NET Web API attributes
- Controller classes:
RoutePrefixAttribute
on the controller classDescriptionAttribute
on the controller class (used to fill the Swagger 'Summary')
- Action methods:
RouteAttribute
andActionNameAttribute
on the action method, with support for Route constraints (e.g.[Route("users/{id:int}"]
)DescriptionAttribute
on the action method (used as Swagger operation 'Description')- One or more
ProducesResponseTypeAttribute
on the action method - HTTP verb attributes:
AcceptVerbsAttribute
HttpGetAttribute
HttpPostAttribute
HttpPutAttribute
HttpDeleteAttribute
HttpOptionsAttribute
- Action method parameters:
FromBodyAttribute
on the action method parameterModelBinderAttribute
The generator also supports data annotations, check out this page for more information.
Additionally supported attributes
- Package: NSwag.Annotations
SwaggerResponseAttribute(httpAction, type)
Defines the response type of a Web API action method and HTTP action. See Specify the response type of an action.
SwaggerDefaultResponseAttribute()
Adds the default response (HTTP 200/204) based on the return type of the operation method. This can be used in conjunction with the SwaggerResponseAttribute
or another response defining attribute (ProducesResponseTypeAttribute
, etc.). This is needed because if one of these attributes is available, you have to define all responses and the default response is not automatically added. If an HTTP 200/204 response is already defined then the attribute is ignored (useful if the attribute is defined on the controller or the base class).
SwaggerIgnoreAttribute()
Excludes a Web API method from the Swagger specification.
SwaggerOperationAttribute(operationId)
Defines a custom operation ID for a Web API action method.
SwaggerTagsAttribute(tags)
Defines the operation tags. See Specify the operation tags.
SwaggerExtensionDataAttribute()
Adds extension data to the document (when applied to a controller class), an operation or parameter.
- Package: NJsonSchema
NotNullAttribute and CanBeNullAttribute
Can be defined on DTO properties (handled by NJsonSchema), operation parameters and the return type with:
[return: NotNull]
public string GetName()
The default behavior can be changed with the WebApiToSwaggerGeneratorSettings.DefaultReferenceTypeNullHandling
setting (default: Null).
Serve the Swagger specification from a Web API action
You should use the OWIN middlewares to serve a Swagger specifications via HTTP.
You can serve the Swagger specification by running the Swagger generator in a Web API action method:
[RoutePrefix("api/MyWebApi")]
public class MyWebApiController : ApiController
{
// TODO: Add action methods here private static readonly Lazy<string> _swagger = new Lazy<string>(() =>
{
var settings = new WebApiToSwaggerGeneratorSettings
{
DefaultUrlTemplate = "api/{controller}/{action}/{id}"
}; var generator = new WebApiToSwaggerGenerator(settings);
var document = Task.Run(async () => await generator.GenerateForControllerAsync<MyWebApiController>())
.GetAwaiter().GetResult(); return document.ToJson();
}); [SwaggerIgnore]
[HttpGet, Route("swagger/docs/v1")]
public HttpResponseMessage Swagger()
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent(_swagger.Value, Encoding.UTF8, "application/json");
return response;
}
}
The Swagger specification can now be accessed via the path http://myhost/api/MyWebApi/swagger/docs/v1
.
The following code shows how to implemented a controller which serves the Swagger specification for multiple controllers: (这个更靠谱)
public class SwaggerController : Controller
{
private static readonly Lazy<string> _swagger = new Lazy<string>(() =>
{
var controllers = new[] { typeof(FooController), typeof(BarController) };
var settings = new WebApiToSwaggerGeneratorSettings
{
DefaultUrlTemplate = "api/{controller}/{action}/{id}"
}; var generator = new WebApiToSwaggerGenerator(settings);
var document = Task.Run(async () => await generator.GenerateForControllersAsync(controllers))
.GetAwaiter().GetResult(); return document.ToJson();
}); [SwaggerIgnore]
[HttpGet, Route("swagger/docs/v1")]
public HttpResponseMessage Swagger()
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent(_swagger.Value, Encoding.UTF8, "application/json");
return response;
}
}
NSwag给api加上说明的更多相关文章
- .NET Core 3.0 使用Nswag生成Api文档和客户端代码
摘要 在前后端分离.Restful API盛行的年代,完美的接口文档,成了交流的纽带.在项目中引入Swagger (也称为OpenAPI),是种不错的选择,它可以让接口数据可视化.下文将会演示 利用N ...
- 使用PHP创建一个REST API(译)
最近API在网络领域有些风靡,明确的说是REST的影响力.这实在没什么好惊讶的,因为在任何编程语言中,消费REST API都是非常的容易.构建它也非常的简单,因为本质上你不会用到任何那些已存在很久的H ...
- Dingo Api 1.0在laravel5.2中的简单应用
Dingo Api是为基于laravel的开发提供了一系列工具集,这些工具集可以帮助开发者快速构建API.Dingo Api最新的版本是2.0.0-alpha1,这个版本需要php7.0以上的php版 ...
- Taro 压缩图片api
Taro API里面没有写支持compressImage,ts提示也是,开发者工具提示暂时不支持此API调试,请使用真机进行开发.这是因为Taro这个库没有把新的api加上,其实还是调用了wx.com ...
- 微服务架构学习与思考(10):微服务网关和开源 API 网关01-以 Nginx 为基础的 API 网关详细介绍
微服务架构学习与思考(10):微服务网关和开源 API 网关01-以 Nginx 为基础的 API 网关详细介绍 一.为什么会有 API Gateway 网关 随着微服务架构的流行,很多公司把原有的单 ...
- 跟随 Web 标准探究DOM -- Node 与 Element 的遍历
写在前面 这篇没有什么 WebKit 代码的分析,因为……没啥好分析的,在实现里无非就是树的(先序DFS)遍历而已,囧哈哈哈……在WebCore/dom/Node.h , WebCore/dom/Co ...
- java J2EE与DiscuzX3.2的UCenter实现单点登录
最近笔者在实现Java项目对discuz的整合.在此过程中,查了很多这方面的资料,发现网上并没有说得比较全面的文章.笔者博取众长以及自己在此过程中遇到的问题,写下来供大家参考,希望大家可以在这过程中少 ...
- 控制器中获取store
在Controller中要获取View中的选中值我用[javascript] view plaincopyprint?var cmp = Ext.ComponentQuery.query('weldl ...
- Why Apache Beam? A data Artisans perspective
https://cloud.google.com/dataflow/blog/dataflow-beam-and-spark-comparison https://github.com/apache/ ...
随机推荐
- jQuery中的ajax用法案例
什么是 AJAX? AJAX = 异步 JavaScript 和 XML(Asynchronous JavaScript and XML). 简短地说,在不重载整个网页的情况下,AJAX 通过后台加载 ...
- PHP中new static()与new self()的区别异同
self - 就是这个类,是代码段里面的这个类. static - PHP 5.3加进来的只得是当前这个类,有点像$this的意思,从堆内存中提取出来,访问的是当前实例化的那个类,那么 static ...
- SNMP信息泄露漏洞
SNMP协议简介 名称:SNMP(Simple Network Management Protocol)简单网络管理协议 端口:161 协议:UDP 用途:SNMP代理者以变量呈现管理资料.管理系统透 ...
- Rsync匿名访问漏洞
前言 前两天总结了互联网或者说IT公司内网常见的漏洞,然后决定针对还没学习过不了解的漏洞进行学习了解,所以准备一一针对来研习,今天是第一篇,立一个Flag,争取今年搞定,为啥说的这么艰难,因为平时工作 ...
- 网页头部的声明应该是用 lang="";
我们经常需要用缩写的代码来表示一种语言,比如用en表示英语,用de表示德语.ISO 639就是规定语种代码的国际标准.最早的时候,ISO 639规定的代码是,用两个拉丁字母表示一种语言,这被称为ISO ...
- 微信小程序 --- toast消息提示框
toast:是用于进行提示用户的: 效果: 代码: <toast hidden="{{onOff}}" duration="1000" bindchang ...
- JAVA内存构成详解
java memory = direct memory(直接内存) + jvm memory(MaxPermSize +Xmx) 1)直接内存跟堆 直接内存则是一块由程序本身管理的一块内存空间,它 ...
- postgresql----SELECT
示例1.简单查询 使用*查询表所有的字段,也可以指定字段名查询 test=# select * from tbl_insert; a | b ---+---- | sd | ff ( rows) te ...
- 【转】SQL Server编程游标
在关系数据库中,我们对于查询的思考是面向集合的.而游标打破了这一规则,游标使得我们思考方式变为逐行进行.对于类C的开发人员来着,这样的思考方式会更加舒服. 正常面向集合的思维方式是: 而对于游标来说: ...
- Apache POI 读写 Excel 文件
目录 写入 Excel 文件 读取 Excel 文件 遍历 Excel 文件 需要的 maven 依赖 完整代码 写入 Excel 文件 // 写入 Excel 文件 // ============= ...