ASP.NET Core Web API 描述文档-使用Swagger
2016-12-09 14:15
971 查看
1.获取Swagger的引用包:
右击项目:Manage Nuget Packages:
输入Swashbuckle:
点击安装
2.将Swagger加入到.net core的中间件Middleware中:
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddLogging();
// Add our repository type
services.AddSingleton<ITodoRepository, TodoRepository>();
// Inject an implementation of ISwaggerProvider with defaulted settings applied
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}3.在浏览器中输入:
可以看到Swagger的Json描述文件:
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "API V1"
},
"basePath": "/",
"paths": {
"/api/Todo": {
"get": {
"tags": [
"Todo"
],
"operationId": "ApiTodoGet",
"consumes": [],
"produces": [
"text/plain",
"application/json",
"text/json"
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/TodoItem"
}
}
}
},
"deprecated": false
},
"post": {
...
}
},
"/api/Todo/{id}": {
"get": {
...
},
"put": {
...
},
"delete": {
...
},
"definitions": {
"TodoItem": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"name": {
"type": "string"
},
"isComplete": {
"type": "boolean"
}
}
}
},
"securityDefinitions": {}
}
4.定位到:
5.自定义和扩展 API Info和Description:
startup.cs:ConfigureService方法中:
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
});
6.显示方法的描述信息:xml comments:
在vs中启用Xml Comments功能:
项目-》属性-》build-》勾选XML documentation file:
startup.cs:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddLogging();
// Add our repository type.
services.AddSingleton<ITodoRepository, TodoRepository>();
// Inject an implementation of ISwaggerProvider with defaulted settings applied.
services.AddSwaggerGen();
// Add the detail information for the API.
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
//Determine base path for the application.
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
//Set the comments path for the swagger json and ui.
var xmlPath = Path.Combine(basePath, "TodoApi.xml");
options.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}
给方法加remarks标签:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Note that the key is a GUID and not an integer.
///
/// POST /Todo
/// {
/// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>New Created Todo Item</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(typeof(TodoItem), 201)]
[ProducesResponseType(typeof(TodoItem), 400)]
public IActionResult Create([FromBody, Required] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
TodoItems.Add(item);
return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
}
给实体类加特性:Annotations
namespace TodoApi.Models
{
public class TodoItem
{
public string Key { get; set; }
[Required]
public string Name { get; set; }
[DefaultValue(false)]
public bool IsComplete { get; set; }
}
}
7.修改Swagger的UI:
通过Nuget 引用Microsoft.AspNetCore.StaticFiles包:
startup.cs:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Enable static files middleware.
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}
从https://github.com/aspnet/Docs/tree/master/aspnetcore/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui获取index.html和custom.css 文件
右击项目:Manage Nuget Packages:
输入Swashbuckle:
点击安装
2.将Swagger加入到.net core的中间件Middleware中:
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddLogging();
// Add our repository type
services.AddSingleton<ITodoRepository, TodoRepository>();
// Inject an implementation of ISwaggerProvider with defaulted settings applied
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}3.在浏览器中输入:
http://localhost:<random_port>/swagger/v1/swagger.json
可以看到Swagger的Json描述文件:
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "API V1"
},
"basePath": "/",
"paths": {
"/api/Todo": {
"get": {
"tags": [
"Todo"
],
"operationId": "ApiTodoGet",
"consumes": [],
"produces": [
"text/plain",
"application/json",
"text/json"
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/TodoItem"
}
}
}
},
"deprecated": false
},
"post": {
...
}
},
"/api/Todo/{id}": {
"get": {
...
},
"put": {
...
},
"delete": {
...
},
"definitions": {
"TodoItem": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"name": {
"type": "string"
},
"isComplete": {
"type": "boolean"
}
}
}
},
"securityDefinitions": {}
}
4.定位到:
http://localhost:<random_port>/swagger/ui,看到Swagger UI:自动显示了API中所有的方法:
5.自定义和扩展 API Info和Description:
startup.cs:ConfigureService方法中:
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
});
6.显示方法的描述信息:xml comments:
在vs中启用Xml Comments功能:
项目-》属性-》build-》勾选XML documentation file:
startup.cs:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddLogging();
// Add our repository type.
services.AddSingleton<ITodoRepository, TodoRepository>();
// Inject an implementation of ISwaggerProvider with defaulted settings applied.
services.AddSwaggerGen();
// Add the detail information for the API.
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "ToDo API",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
License = new License { Name = "Use under LICX", Url = "http://url.com" }
});
//Determine base path for the application.
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
//Set the comments path for the swagger json and ui.
var xmlPath = Path.Combine(basePath, "TodoApi.xml");
options.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}
/// <summary> /// Deletes a specific TodoItem. /// </summary> /// <param name="id"></param> [HttpDelete("{id}")] public void Delete(string id) { TodoItems.Remove(id); }
给方法加remarks标签:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Note that the key is a GUID and not an integer.
///
/// POST /Todo
/// {
/// "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>New Created Todo Item</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(typeof(TodoItem), 201)]
[ProducesResponseType(typeof(TodoItem), 400)]
public IActionResult Create([FromBody, Required] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
TodoItems.Add(item);
return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
}
给实体类加特性:Annotations
namespace TodoApi.Models
{
public class TodoItem
{
public string Key { get; set; }
[Required]
public string Name { get; set; }
[DefaultValue(false)]
public bool IsComplete { get; set; }
}
}
7.修改Swagger的UI:
通过Nuget 引用Microsoft.AspNetCore.StaticFiles包:
startup.cs:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Enable static files middleware.
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
}
从https://github.com/aspnet/Docs/tree/master/aspnetcore/tutorials/web-api-help-pages-using-swagger/sample/src/TodoApi/wwwroot/swagger/ui获取index.html和custom.css 文件
相关文章推荐
- ASP.NET Core 中文文档 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档
- Asp.net Core WebApi 使用Swagger做帮助文档,并且自定义Swagger的UI
- ASP.NET Web API 使用Swagger生成在线帮助测试文档
- ASP.NET Core 1.0 中使用 Swagger 生成文档
- ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET
- 在ASP.NET Core Web API上使用Swagger提供API文档
- 在ASP.NET Core Web API上使用Swagger提供API文档
- asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档
- 使用Swagger来生成asp.net core Web API 文档
- 在ASP.NET Core Web API上使用Swagger提供API文档
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
- ASP.NET Core WebApi使用Swagger生成api说明文档看这篇就够了
- ASP.NET Web API 使用Swagger生成在线帮助测试文档
- asp.net core 使用 swagger 生成接口文档
- ASP.NET Web API 使用Swagger生成在线帮助测试文档
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
- ASP.NET Web API 使用Swagger生成在线帮助测试文档
- 在ASP.NET Core Web API上使用Swagger提供API文档
- ASP.NET Core 中文文档 第二章 指南(8) 使用 dotnet watch 开发 ASP.NET Core 应用程序
- 用Swashbuckle给ASP.NET Core的项目自动生成Swagger的API帮助文档