第一步:创建API项目 步骤这里不说明
第二步:就是Nuget 包,
两种方式:1、工具-》Nuget管理-》程序包管理控制台 Install-Package Swashbuckle.AspNetCore
2、工具-》Nuget管理-》管理Nuget包... 或者右击项目。。。 输入 Swashbuckle.AspNetCore
第三步:全局配置,这里以最简单的配置为例
在Startup.cs 文件下 ConfigureService 下添加如下代码
services.AddSwaggerGen(opt => { opt.SwaggerDoc("v1", new Info { Title = "MyFirstApi", Version = "v1" }); });
在Configure 下添加如下代码
app.UseSwagger(); app.UseSwaggerUI(opt => { opt.SwaggerEndpoint("/swagger/v1/swagger.json", "MyFirstApi"); });
第四步:编写自己的接口
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DoNetCoreApiSwagger.Controllers { [Route("api/[controller]")] [ApiController] public class userController : ControllerBase { private static List<User> listUser = null; public userController() { listUser.AddRange(new List<User> { new User(){ Id=1,userName="zhansan"} }); } [HttpGet("getuserlist")] public async Task<object> GetUserList(int userid) { return await Task.Run<object>(()=> { return new {code=200,data= listUser.FindAll(a=>a.Id==userid) }; }); } [HttpPost("adduser")] public async Task<object> AddUser([FromBody]User user) { return await Task.Run<object>(() => { listUser.Add(user); return new { code = 200, data="添加成功" }; }); } } public class User { public int Id { get; set; } public string userName { get; set; } } }
第五步:配置路由,但这里不进行配置了,就以修改文件的形式进行调整
修改launchSettings.json 文件
如下:
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:5000", "sslPort": 0 } }, "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger/", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "DoNetCoreApiSwagger": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger/", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:5000" } } }
原文地址:https://www.cnblogs.com/KenFine/p/10663100.html
时间: 2024-10-11 05:22:21