标签:rtu ret swagger document 开启 文档 route 改变 json
swagger的主要作用是API接口文档+接口调试的作用
在WeatherForecastController里加了另外4个方法,如何调用接口呢?如何进行断点调试呢?
/// <summary> /// 查询 /// </summary> /// <returns></returns> [HttpGet] 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(); } /// <summary> /// 根据id查询 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "Get by id"; } /// <summary> /// 新增 /// </summary> /// <param name="value"></param> /// <returns></returns> [HttpPost] public ActionResult<string> Post([FromBody] string value) { return "Insert"; } /// <summary> /// 修改 /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns></returns> [HttpPut("{id}")] public ActionResult<string> Put(int id, [FromBody] string value) { return "Edit"; } /// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id}")] public ActionResult<string> Delete(int id) { return "Delete by id"; }
首先,项目右键编辑项目文件,写如下代码,表示把注释生成到指定目录下的XML文件里
<PropertyGroup Condition="‘$(Configuration)|$(Platform)‘==‘Debug|AnyCPU‘"> <DocumentationFile>bin\Debug\net5.0\EmptyTemplate.APICore.xml</DocumentationFile> <OutputPath>bin\Debug\net5.0\</OutputPath> </PropertyGroup> <PropertyGroup Condition="‘$(Configuration)|$(Platform)‘==‘Release|AnyCPU‘"> <DocumentationFile>bin\Release\net5.0\EmptyTemplate.APICore.xml</DocumentationFile> <OutputPath>bin\Release\net5.0\</OutputPath> </PropertyGroup>
然后,Startup 的ConfigureServices 里配置swagger
#region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "EmptyTemplate.Api", Version = "v1" }); //导入XML文件信息 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath,true); }); #endregion
首先,launchSettings.json 文件里,把launchUrl改为空
然后,Startup的Configure里开启swagger
#region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "EmptyTemplate.Api V1"); c.RoutePrefix = ""; //路径配置,首页配置为swagger首页,去launchSettings.json把launchUrl去掉 }); #endregion
项目的起始文件改变了,不再是之前的 WeatherForecast,而是http://localhost:50853/index.html,并且每个Action上的注释都显示出来了
我们在Post方法里设置断点,然后点击页面上Post方法后面的Try it out,然后输入入参,点击Excute,断点就进入方法里了。
这一点后面学授权时再补充。
这种更适用于调用别人的接口时使用
以后有时间再补充。
标签:rtu ret swagger document 开启 文档 route 改变 json
原文地址:https://www.cnblogs.com/WorkhardNi/p/14680525.html