• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.netmvc5中使用Swagger自动生成WebApi文档笔记

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Swagger可以自动生成Api说明文档,并内置在线测试,通过NSwagStudio还可以自动生成Api客户端调用代码,以下为具体实现步骤

1、写一个简单的WebApi并加上注释

 1  public class ValuesController : ApiController
 2     {
 3   
 4         /// <summary>
 5         /// 这是一个Post测试
 6         /// </summary>
 7         /// <param name="para"></param>
 8         /// <returns></returns>
 9         [HttpPost]
10         public JsonResult<object> GetJsonValue([FromBody]InputValue para)
11         {
12             using (IDbConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
13             {
14                 cn.Open();
15                 var ret = SqlMapper.Query(cn, "select * from AbpRoles where Id = @id", new { Id = para.Id });
16                 return Json<object>(ret);
17             }
18         }
19 
20 
21         /// <summary>
22         /// 传入参数
23         /// </summary>
24         public class InputValue
25         {
26             /// <summary>
27             /// 主键
28             /// </summary>
29             public int Id { get; set; }
30             /// <summary>
31             /// 名称
32             /// </summary>
33             public string Name { get; set; }
34         }
35     }
View Code

 

2、首先要配置项目可以生成XML说明文档,右击你的项目->生成->输出->勾上 XML文档文件 然后把这个文件名放在下面的代码里.

3、然后 在Areas/HelpPage/App_Start/HelpPageConfig.cs 文件中目前应该是第62行. 增加下面的代码

config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/MvcWebApi01.xml")));

4、安装Swagger

Install-Package Swashbuckle -Version 5.6.0

5、添加导航链接

在_Layout.cshtml文件中添加代码,测试api地址为 http://yourserver/swagger
<li>@Html.ActionLink("Swagger Help", "", "Swagger", new { area = "" }, null)</li>
 
6、修改SwaggerConfig.cs文件
 安装完成后,在文件夹App_Start自动生成一个配置文件 swagger.config。这里可以做多版本控制,定义扩展功能,自定义显示ui的样式脚本,可以配置过滤、权限等。
    string path = string.Format("{0}/bin/MvcWebApi01.xml", System.AppDomain.CurrentDomain.BaseDirectory);
                        c.IncludeXmlComments(path);

 

7、在线测试WebApi,文档注释会自动显示

8、下载NSwagStudio,https://github.com/RSuter/NSwag

9、输入swagger地址,http://localhost/MvcWebApi01/swagger/docs/v1,点击生成即可自动生成ts、c# client 、c# web api controler三种类型的调用客户端

 

 下面为生成的代码地址

   1 //----------------------
   2 // <auto-generated>
   3 //     Generated using the NSwag toolchain v11.17.21.0 (NJsonSchema v9.10.63.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
   4 // </auto-generated>
   5 //----------------------
   6 
   7 namespace MyNamespace
   8 {
   9 #pragma warning disable // Disable all warnings
  10 
  11     [System.CodeDom.Compiler.GeneratedCode("NSwag", "11.17.21.0 (NJsonSchema v9.10.63.0 (Newtonsoft.Json v9.0.0.0))")]
  12     public partial class ValuesClient
  13     {
  14         private string _baseUrl = "http://localhost/MvcWebApi01";
  15         private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
  16 
  17         public ValuesClient(string baseUrl)
  18         {
  19             _baseUrl = baseUrl;
  20             _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() =>
  21             {
  22                 var settings = new Newtonsoft.Json.JsonSerializerSettings();
  23                 UpdateJsonSerializerSettings(settings);
  24                 return settings;
  25             });
  26         }
  27 
  28         public string BaseUrl
  29         {
  30             get { return _baseUrl; }
  31             set { _baseUrl = value; }
  32         }
  33 
  34         protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } }
  35 
  36         partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings);
  37         partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url);
  38         partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder);
  39         partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
  40 
  41         /// <returns>OK</returns>
  42         /// <exception cref="SwaggerException">A server side error occurred.</exception>
  43         public System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<string>> GetAllAsync()
  44         {
  45             return GetAllAsync(System.Threading.CancellationToken.None);
  46         }
  47 
  48         /// <returns>OK</returns>
  49         /// <exception cref="SwaggerException">A server side error occurred.</exception>
  50         /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
  51         public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<string>> GetAllAsync(System.Threading.CancellationToken cancellationToken)
  52         {
  53             var urlBuilder_ = new System.Text.StringBuilder();
  54             urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Values/Get");
  55 
  56             var client_ = new System.Net.Http.HttpClient();
  57             try
  58             {
  59                 using (var request_ = new System.Net.Http.HttpRequestMessage())
  60                 {
  61                     request_.Method = new System.Net.Http.HttpMethod("GET");
  62                     request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  63 
  64                     PrepareRequest(client_, request_, urlBuilder_);
  65                     var url_ = urlBuilder_.ToString();
  66                     request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
  67                     PrepareRequest(client_, request_, url_);
  68 
  69                     var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  70                     try
  71                     {
  72                         var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
  73                         if (response_.Content != null && response_.Content.Headers != null)
  74                         {
  75                             foreach (var item_ in response_.Content.Headers)
  76                                 headers_[item_.Key] = item_.Value;
  77                         }
  78 
  79                         ProcessResponse(client_, response_);
  80 
  81                         var status_ = ((int)response_.StatusCode).ToString();
  82                         if (status_ == "200")
  83                         {
  84                             var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
  85                             var result_ = default(System.Collections.ObjectModel.ObservableCollection<string>);
  86                             try
  87                             {
  88                                 result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<string>>(responseData_, _settings.Value);
  89                                 return result_;
  90                             }
  91                             catch (System.Exception exception_)
  92                             {
  93                                 throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
  94                             }
  95                         }
  96                         else
  97                         if (status_ != "200" && status_ != "204")
  98                         {
  99                             var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
 100                             throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
 101                         }
 102 
 103                         return default(System.Collections.ObjectModel.ObservableCollection<string>);
 104                     }
 105                     finally
 106                     {
 107                         if (response_ != null)
 108                             response_.Dispose();
 109                     }
 110                 }
 111             }
 112             finally
 113             {
 114                 if (client_ != null)
 115                     client_.Dispose();
 116             }
 117         }
 118 
 119         /// <returns>OK</returns>
 120         /// <exception cref="SwaggerException">A server side error occurred.</exception>
 121         public System.Threading.Tasks.Task<string> GetAsync(int id)
 122         {
 123             return GetAsync(id, System.Threading.CancellationToken.None);
 124         }
 125 
 126         /// <returns>OK</returns>
 127         /// <exception cref="SwaggerException">A server side error occurred.</exception>
 128         /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 129         public async System.Threading.Tasks.Task<string> GetAsync(int id, System.Threading.CancellationToken cancellationToken)
 130         {
 131             if (id == null)
 132                 throw new System.ArgumentNullException("id");
 133 
 134             var urlBuilder_ = new System.Text.StringBuilder();
 135             urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Values/Get/{id}");
 136             urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));
 137 
 138             var client_ = new System.Net.Http.HttpClient();
 139             try
 140             {
 141                 using (var request_ = new System.Net.Http.HttpRequestMessage())
 142                 {
 143                     request_.Method = new System.Net.Http.HttpMethod("GET");
 144                     request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
 145 
 146                     PrepareRequest(client_, request_, urlBuilder_);
 147                     var url_ = urlBuilder_.ToString();
 148                     request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 149                     PrepareRequest(client_, request_, url_);
 150 
 151                     var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
 152                     try
 153                     {
 154                         var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
 155                         if (response_.Content != null && response_.Content.Headers != null)
 156                         {
 157                             foreach (var item_ in response_.Content.Headers)
 158                                 headers_[item_.Key] = item_.Value;
 159                         }
 160 
 161                         ProcessResponse(client_, response_);
 162 
 163                         var status_ = ((int)response_.StatusCode).ToString();
 164                         if (status_ == "200")
 165                         {
 166                             var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
 167                             var result_ = default(string);
 168                             try
 169                             {
 170                                 result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(responseData_, _settings.Value);
 171                                 return result_;
 172                             }
 173                             catch (System.Exception exception_)
 174                             {
 175                                 throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
 176                             }
 177                         }
 178                         else
 179                         if (status_ != "200" && status_ != "204")
 180                         {
 181                             var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
 182                             throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
 183                         }
 184 
 185                         return default(string);
 186                     }
 187                     finally
 188                     {
 189                         if (response_ != null)
 190                             response_.Dispose();
 191                     }
 192                 }
 193             }
 194             finally
 195             {
 196                 if (client_ != null)
 197                     client_.Dispose();
 198             }
 199         }
 200 
 201         /// <returns>No Content</returns>
 202         /// <exception cref="SwaggerException">A server side error occurred.</exception>
 203         public System.Threading.Tasks.Task PostAsync(string value)
 204         {
 205             return PostAsync(value, System.Threading.CancellationToken.None);
 206         }
 207 
 208         /// <returns>No Content</returns>
 209         /// <exception cref="SwaggerException">A server side error occurred.</exception>
 210         /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 211         public async System.Threading.Tasks.Task PostAsync(string value, System.Threading.CancellationToken cancellationToken)
 212         {
 213             var urlBuilder_ = new System.Text.StringBuilder();
 214             urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Values/Post");
 215 
 216             var client_ = new System.Net.Http.HttpClient();
 217             try
 218             {
 219                 using (var request_ = new System.Net.Http.HttpRequestMessage())
 220                 {
 221                     var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(value, _settings.Value));
 222                     content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
 223                     request_.Content = content_;
 224                     request_.Method = new System.Net.Http.HttpMethod("POST");
 225 
 226                     PrepareRequest(client_, request_, urlBuilder_);
 227                     var url_ = urlBuilder_.ToString();
 228                     request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
 229                     PrepareRequest(client_, request_, url_);
 230 
 231                     var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
 232                     try
 233                     {
 234                         var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
 235                         if (response_.Content != null && response_.Content.Headers != null)
 236                         {
 237                             foreach (var item_ in response_.Content.Headers)
 238                                 headers_[item_.Key] = item_.Value;
 239                         }
 240 
 241                         ProcessResponse(client_, response_);
 242 
 243                         var status_ = ((int)response_.StatusCode).ToString();
 244                         if (status_ == "204")
 245                         {
 246                             return;
 247                         }
 248                         else
 249                         if (status_ != "200" && status_ != "204")
 250                         {
 251                             var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
 252                             throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
 253                         }
 254                     }
 255                     finally
 256                     {
 257                         if (response_ != null)
 258                             response_.Dispose();
 259                     }
 260                 }
 261             }
 262             finally
 263             {
 264                 if< 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap