前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >asp.net core 3.1/swagger

asp.net core 3.1/swagger

作者头像
雪飞鸿
发布2020-05-25 11:09:26
5150
发布2020-05-25 11:09:26
举报
文章被收录于专栏:me的随笔me的随笔

本文使用特性来描述接口而不是xml文件,使用特性可自定义接口在swaggerUI上的描述

安装nuget包:Swashbuckle.AspNetCore.SwaggerUISwashbuckle.AspNetCore.Annotations,配置swagger:

代码语言:javascript
复制
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
​
namespace swaggerweb
{
    public class Startup
    {
        private readonly string swaggerDocName = "weather";
​
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
​
        public IConfiguration Configuration { get; }
​
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(opt =>
            {
                opt.SwaggerDoc(swaggerDocName, new OpenApiInfo()
                {
                    Version = "v1",
                    Title = "WeatherForecast",
                    Description = "天气预报"
                });
                // 使用annotation来描述接口,不依赖XML文件
                opt.EnableAnnotations();
​
                // 下面两句,将swagger文档中controller名使用GroupName替换
                // 在Swagger中,一个Tag可以看作是一个API分组
                opt.DocInclusionPredicate((_, apiDescription) => string.IsNullOrWhiteSpace(apiDescription.GroupName) == false);
                opt.SwaggerGeneratorOptions.TagsSelector = (apiDescription) => new[] { apiDescription.GroupName };
            });
            services.AddControllers();
        }
​
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSwagger(opt =>
            {
                // 相对路径加载swagger文档
                //opt.RouteTemplate = "swagger/{documentName}";
            })
            .UseSwaggerUI(opt =>
            {
                opt.SwaggerEndpoint($"{swaggerDocName}/swagger.json", "天气预报API文档");
            });
​
            app.UseRouting();
​
            app.UseAuthorization();
​
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                // 也可以在这里配置swagger文档路径
                //endpoints.MapSwagger();
            });
        }
    }
}

Controller和Action上使用特性:ApiExplorerSettingsSwaggerOperation

代码语言:javascript
复制
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
​
namespace swaggerweb.Controllers
{
    [ApiExplorerSettings(GroupName = "天气预报")]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
​
        private readonly ILogger<WeatherForecastController> _logger;
​
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
​
        [HttpGet]
        [SwaggerOperation(Summary = "获取天气预报信息")]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

效果图:

推荐阅读

Grouping Operations With Tags

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档