码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现

时间:2016-07-22 14:34:08      阅读:952      评论:0      收藏:0      [点我收藏+]

标签:

from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/

代码生成工具: https://github.com/NSwag/NSwag 

 

This article shows how to document your ASP.NET Core 1.0 MVC API using Swagger with Swashbuckle. Per default, it does not use your xml comments in the code and this needs to be configured if required.

 

Code: https://github.com/damienbod/AspNet5GeoElasticsearch

2016.07.03 Updated to ASP.NET Core RTM
2016.06.04 Updated to ASP.NET Core RC2 dotnet

Step 1: Add the required NuGet packages to the dependencies in the project.json file.

1
2
3
4
5
6
"dependencies": {
 
        "Swashbuckle.SwaggerGen": "6.0.0-beta901",
        "Swashbuckle.SwaggerUi": "6.0.0-beta901"
 
},

Step 2: Produce the .xml file which contains the xml comments when building. Click the produce outputs on build checkbox in your project file.

技术分享

Or set the ProduceOutputsOnBuild property in the project xproj file.

1
<ProduceOutputsOnBuild>True</ProduceOutputsOnBuild>

Step 3: Configure Swashbuckle.SwaggerGen in the Startup class ConfigureServices method.

You need to define your path to the comments xml file, which can be found in the artifacts folder. This should be saved in a config file.

The ConfigureSwaggerDocument with OperationFilter method is required so that the xml comments are added to the documentation, and also ConfigureSwaggerSchema with ModelFilter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void ConfigureServices(IServiceCollection services)
{
    var pathToDoc = Configuration["Swagger:Path"];
 
    services.AddMvc();
 
    services.AddSwaggerGen();
    services.ConfigureSwaggerGen(options =>
    {
        options.SingleApiVersion(new Info
        {
            Version = "v1",
            Title = "Geo Search API",
            Description = "A simple api to search using geo location in Elasticsearch",
            TermsOfService = "None"
        });
        options.IncludeXmlComments(pathToDoc);
        options.DescribeAllEnumsAsStrings();
    });
 
    services.AddScoped<ISearchProvider, SearchProvider>();
}

Step 4: Use swagger in the Startup class Configure method.

UseSwaggerGen and UseSwaggerUi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
 
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
 
    app.UseStaticFiles();
 
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
 
    app.UseSwagger();
        app.UseSwaggerUi();
}

Step 5: Create a Controller API with your documentation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using Microsoft.AspNet.Mvc;
using AspNet5GeoElasticsearch.ElasticsearchApi;
using AspNet5GeoElasticsearch.Models;
 
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
 
namespace AspNet5GeoElasticsearch.Controllers
{
    /// <summary>
    /// This class is used as an api for the search requests.
    /// </summary>
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class SearchController : Controller
    {
        private readonly ISearchProvider _searchProvider;
 
        public SearchController(ISearchProvider searchProvider)
        {
            _searchProvider = searchProvider;
        }
 
        /// <summary>
        /// This method returns the found documents from Elasticsearch
        /// </summary>
        /// <param name="maxDistanceInMeter">Distance in meters from your location</param>
        /// <param name="centerLongitude">center Longitude </param>
        /// <param name="centerLatitude">center Latitude </param>
        /// <returns>All the documents which were found</returns>
        [HttpGet]
        [Produces(typeof(MapModel))]
        [SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(MapModel))]
        [Route("GeoSearch")]
        public ActionResult Search(uint maxDistanceInMeter, double centerLongitude, double centerLatitude)
        {
            var searchResult = _searchProvider.SearchForClosest(maxDistanceInMeter, centerLongitude, centerLatitude);
            var mapModel = new MapModel
            {
                MapData = JsonConvert.SerializeObject(searchResult),
                CenterLongitude = centerLongitude,
                CenterLatitude = centerLatitude,
                MaxDistanceInMeter = maxDistanceInMeter
            };
 
            return Ok(mapModel);
        }
 
        /// <summary>
        /// Inits the Elasticsearch documents
        /// </summary>
        [HttpPost]
        [Route("InitData")]
        public ActionResult InitData()
        {
            initSearchEngine();
            return Ok();
        }
 
        private void initSearchEngine()
        {
            if (!_searchProvider.MapDetailsIndexExists())
            {
                _searchProvider.InitMapDetailMapping();
                _searchProvider.AddMapDetailData();
            }
        }
    }
}

This can then be viewed using ./swagger/ui

http://localhost:21453/swagger/ui/index.html

技术分享

Links:

https://github.com/domaindrivendev/Swashbuckle

https://github.com/domaindrivendev/Ahoy

http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField/

ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现

标签:

原文地址:http://www.cnblogs.com/94cool/p/5694881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!