您的位置:首页 > 编程语言 > ASP

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.在浏览器中输入:
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 文件



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: