参考http://petstore.swagger.io

给controller加上description

https://github.com/RSuter/NSwag/issues/1803

xml summary

https://github.com/RSuter/NJsonSchema/wiki/XML-Documentation

WebApiToSwaggerGenerator

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 class
    • DescriptionAttribute on the controller class (used to fill the Swagger 'Summary')
  • Action methods:
    • RouteAttribute and ActionNameAttribute 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 parameter
    • ModelBinderAttribute

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;
}
}

最新文章

  1. Redis数据结构详解(一)
  2. python遍历一个网段的ip地址
  3. 解决:/bin/bash: mvn: 未找到命令
  4. HBase简介
  5. AR , VR, GVR ...
  6. html5中上传图片
  7. EMVTag系列14《支付环境响应数据》
  8. httpclient的get带参不带参post带参不带参的简单应用
  9. CAD版本 注册表信息
  10. 多线程处理慢sql查询小笔记~
  11. 在SpringTest中将Mockito的mock对象通过spring注入使用
  12. Oracle存储过程生成日期维度
  13. 【WPF/WAF】界面布局(View)文件的多层嵌套(Nest)
  14. cesium图形上加载图片
  15. Python学习---重点模块的学习【all】
  16. char数组
  17. Bireme:一个 Greenplum数据仓库的增量同步工具
  18. Oracle 10g RAC 如何配置 VIP IPMP
  19. 用OneNote写博客的方法
  20. (七)计算G711语音的打包长度和RTP里timestamp的增长量

热门文章

  1. LeetCode——Balanced Binary Tree
  2. Linux性能监控——CPU,Memory,IO,Network
  3. 关于Android原生Email的自己的一些认识
  4. Splay模板 1.0
  5. 【黑金ZYNQ7000系列原创视频教程】04.熟悉ZYNQ内部中断——内部定时器中断实验
  6. 使用log4net记录日志到数据库(含有自定义属性)
  7. gradle多项目构建及依赖
  8. nginx软件的编译安装步骤
  9. IT求职部分网站汇总
  10. Mercurial