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

NSwag给api加上说明的更多相关文章

  1. .NET Core 3.0 使用Nswag生成Api文档和客户端代码

    摘要 在前后端分离.Restful API盛行的年代,完美的接口文档,成了交流的纽带.在项目中引入Swagger (也称为OpenAPI),是种不错的选择,它可以让接口数据可视化.下文将会演示 利用N ...

  2. 使用PHP创建一个REST API(译)

    最近API在网络领域有些风靡,明确的说是REST的影响力.这实在没什么好惊讶的,因为在任何编程语言中,消费REST API都是非常的容易.构建它也非常的简单,因为本质上你不会用到任何那些已存在很久的H ...

  3. Dingo Api 1.0在laravel5.2中的简单应用

    Dingo Api是为基于laravel的开发提供了一系列工具集,这些工具集可以帮助开发者快速构建API.Dingo Api最新的版本是2.0.0-alpha1,这个版本需要php7.0以上的php版 ...

  4. Taro 压缩图片api

    Taro API里面没有写支持compressImage,ts提示也是,开发者工具提示暂时不支持此API调试,请使用真机进行开发.这是因为Taro这个库没有把新的api加上,其实还是调用了wx.com ...

  5. 微服务架构学习与思考(10):微服务网关和开源 API 网关01-以 Nginx 为基础的 API 网关详细介绍

    微服务架构学习与思考(10):微服务网关和开源 API 网关01-以 Nginx 为基础的 API 网关详细介绍 一.为什么会有 API Gateway 网关 随着微服务架构的流行,很多公司把原有的单 ...

  6. 跟随 Web 标准探究DOM -- Node 与 Element 的遍历

    写在前面 这篇没有什么 WebKit 代码的分析,因为……没啥好分析的,在实现里无非就是树的(先序DFS)遍历而已,囧哈哈哈……在WebCore/dom/Node.h , WebCore/dom/Co ...

  7. java J2EE与DiscuzX3.2的UCenter实现单点登录

    最近笔者在实现Java项目对discuz的整合.在此过程中,查了很多这方面的资料,发现网上并没有说得比较全面的文章.笔者博取众长以及自己在此过程中遇到的问题,写下来供大家参考,希望大家可以在这过程中少 ...

  8. 控制器中获取store

    在Controller中要获取View中的选中值我用[javascript] view plaincopyprint?var cmp = Ext.ComponentQuery.query('weldl ...

  9. Why Apache Beam? A data Artisans perspective

    https://cloud.google.com/dataflow/blog/dataflow-beam-and-spark-comparison https://github.com/apache/ ...

随机推荐

  1. Egret3D初步学习笔记三 (角色使用)

    一 Unity中编辑角色 仍然使用unity4.7.1_Egret3D_Dll.unitypackage. 里面含有一个角色. 二 查看人物的动画 选中lingtong 属性面板里有个Animator ...

  2. ELK平台介绍

    在搜索ELK资料的时候,发现这篇文章比较好,于是摘抄一小段: 以下内容来自:http://baidu.blog.51cto.com/71938/1676798 日志主要包括系统日志.应用程序日志和安全 ...

  3. 【BZOJ5110】[CodePlus2017]Yazid 的新生舞会 线段树

    [BZOJ5110][CodePlus2017]Yazid 的新生舞会 Description Yazid有一个长度为n的序列A,下标从1至n.显然地,这个序列共有n(n+1)/2个子区间.对于任意一 ...

  4. Unity3D笔记五 快捷键

    一.近距离查看游戏对象 在Hierarchy视图中选择游戏对象,然后在Scene视图中按快捷键“F”来近距离查看该游戏对象. 二.游戏对象不在主摄像头中? Hierarchy中双击选择需要显示的游戏对 ...

  5. Unity3D 笔记一 初始Unity3D

    一.初步认识Unity 1.Unity支持C#.JavaScript.Boo,JavaScript不是标准语法,常称为UnityScript更合适 2.Update 每一帧都会调用该方法.Start. ...

  6. iOS - 常用iOS的第三方框架

    图像:1.图片浏览控件MWPhotoBrowser       实现了一个照片浏览器类似 iOS 自带的相册应用,可显示来自手机的图片或者是网络图片,可自动从网络下载图片并进行缓存.可对图片进行缩放等 ...

  7. 【JavaScript算法】---希尔排序

    一.什么是希尔排序 希尔排序(Shell's Sort)是插入排序的一种又称“缩小增量排序”,是直接插入排序算法的一种更高效的改进版本.   思路:      希尔排序是把记录按下标的一定增量分组,对 ...

  8. javascript飞机大战-----001分析

    1.游戏引擎 首先要做飞机大战要考虑的是这个游戏被分成了哪几大部分?这样我们一块一块去做,特别清晰明了.那么接下来我们就简单的分析下飞机大战分成了哪几大部分 1.游戏引擎 2.英雄机 3.敌机 4.子 ...

  9. ZOJ 3537 Cake(凸包判定+区间DP)

    Cake Time Limit: 1 Second Memory Limit: 32768 KB You want to hold a party. Here's a polygon-shaped c ...

  10. Python开发【Django】:Admin配置管理

    Admin创建登录用户 数据库结构表: from django.db import models # Create your models here. class UserProfile(models ...