ASP.NET Core Web API 描述文档-使用Swagger

1.获取Swagger的引用包:

右击项目:Manage Nuget Packages:


ASP.NET Core Web API 描述文档-使用Swagger_第1张图片

输入Swashbuckle:

ASP.NET Core Web API 描述文档-使用Swagger_第2张图片

点击安装

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();

    // 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:/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:/swagger/ui,看到Swagger UI:自动显示了API中所有的方法:

ASP.NET Core Web API 描述文档-使用Swagger_第3张图片


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

ASP.NET Core Web API 描述文档-使用Swagger_第4张图片


6.显示方法的描述信息:xml comments:

在vs中启用Xml Comments功能:

项目-》属性-》build-》勾选XML documentation file:

ASP.NET Core Web API 描述文档-使用Swagger_第5张图片

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();

    // 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();
    
}

/// 
/// Deletes a specific TodoItem.
/// 
/// 
[HttpDelete("{id}")]
public void Delete(string id)
{
    TodoItems.Remove(id);
}
ASP.NET Core Web API 描述文档-使用Swagger_第6张图片

给方法加remarks标签:

/// 
/// Creates a TodoItem.
/// 
/// 
/// Note that the key is a GUID and not an integer.
///  
///     POST /Todo
///     {
///        "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
///        "name": "Item1",
///        "isComplete": true
///     }
/// 
/// 
/// 
/// New Created Todo Item
/// Returns the newly created item
/// If the item is null
[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);
}


ASP.NET Core Web API 描述文档-使用Swagger_第7张图片

给实体类加特性: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 Web API 描述文档-使用Swagger_第8张图片


ASP.NET Core Web API 描述文档-使用Swagger_第9张图片

你可能感兴趣的:(.NET,Core)