zoukankan      html  css  js  c++  java
  • netcore3.0 webapi集成Swagger 5.0

    今天来尝尝鲜。貌似.net core 3.0使用Swagger 4.0.1会报错,随手一搜,还没人写这个把调试通过的代码贴一下:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.OpenApi.Models;
    using System;
    using System.IO;
    using System.Reflection;
    
    namespace WebApplication4
    {
        public class Startup
        {
            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.AddControllers();
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = ".Net Core中间件API文档", Version = "v1" });
                    // 为 Swagger 设置xml文档注释路径
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                //启用中间件服务生成Swagger
                app.UseSwagger();
                //启用中间件服务生成SwaggerUI,指定Swagger JSON终结点
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", ".Net Core中间件API文档 V1");
                    c.RoutePrefix = string.Empty;//设置根节点访问
                });
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseRouting();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });            
            }
        }
    }

    依赖包:

    控制器:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    
    namespace WebApplication4.Controllers
    {
        /// <summary>
        /// 天气预报API
        /// </summary>
        [ApiController]
        [Route("api/[controller]/[action]")]
        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;
            }
    
            /// <summary>
            /// 获取当前天气
            /// </summary>
            /// <param name="size">城市的个数</param>
            /// <returns></returns>
            [HttpGet]
            [HttpPost]
            public IEnumerable<WeatherForecast> GetWeather(string size = "5")
            {
                var rng = new Random();
                return Enumerable.Range(1, Convert.ToInt32(size)).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }
            /// <summary>
            /// 测试方法
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public ApiResult Demo()
            {
                return new ApiResult
                {
                    Message = "操作成功!",
                    Success = true,
                    Result = 1
                };
            }
        }
    }
  • 相关阅读:
    数据库相关(转)
    sql之left join、right join、inner join的区别
    PHP面试编程
    实验6 shell程序设计一(1)
    实验7 shell程序设计二(1)
    Linux软件安装管理
    Linux常用命令总结
    合唱团
    linux课后作业1
    linux网络服务实验
  • 原文地址:https://www.cnblogs.com/datacool/p/11805585.html
Copyright © 2011-2022 走看看