Asp.net core WebApi 使用Swagger生成接口帮助文档
一.新建一个WebAPI接口,命名为First
测试代码:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace MY.Controllers { /// <summary> /// 严格遵循RestFull 风格 get、post、put、delete /// </summary> [Route("api/[controller]")] [ApiController] // First 当成一个资源 对完提供增删改查的Api public class FirstController : ControllerBase { [Route("Get")] [HttpGet] public string Get() { return "得到一串数据"; } [Route("Info")] [HttpGet] public string Info() { return Newtonsoft.Json.JsonConvert.SerializeObject(new { Id = 1456, Name = "yhh" }); } [Route("GetInfo")] [HttpGet] public string GetInfo(int id,string name) { return Newtonsoft.Json.JsonConvert.SerializeObject(new { Id = id, Name = name }); } } }
二.右键项目依赖项,点击管理Nuget程序包,安装如下图组件
三.在项目Startup添加配置项
/// <summary> /// Core 项目中导出都是IOC + DI /// </summary> public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } /// <summary> /// 被运行时调用的 还有什么? /// 执行且只执行一次; /// </summary> /// <param name="services"></param> // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region 注册Swagger服务 services.AddSwaggerGen(s => { #region 注册 Swagger s.SwaggerDoc("V1", new OpenApiInfo() { Title = "Study", Version = "version-01", Description = "webapi配置swagger学习" }); #endregion }); #endregion 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 使用Swagger中间件 app.UseSwagger(); app.UseSwaggerUI(s => { s.SwaggerEndpoint("/swagger/V1/swagger.json", "test1"); }); #endregion //使用中间件 app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
四.启动项目,然后浏览器输入 http://localhost:50786/swagger/index.html(注:端口和域名依自己的电脑为准)