netcore3.0 webapi集成Swagger 5.0

匿名 (未验证) 提交于 2019-12-03 00:17:01

今天来尝尝鲜。貌似.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             };         }     } }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!