第一步:直接在NuGet里面搜索Swashbuckle.AspNetCore包进行安装:
第二步:在Startup类的ConfigureServices方法里面最后注入服务:services.AddSwaggerGen();
第三步:在Startup类的Configure方法里面添加Swagger有关的中间件
app.UseSwagger();第四步:打开Properties文件夹下面的launchSettings.json里面把launchUrl默认的接口地址改成swagger/index.html即可
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
});
{运行程序即可如下图
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32632",
"sslPort": 44348
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger/index.html",//默认接口地址
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"api": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
services.AddSwaggerGen(options =>然后我们给controller接口添加注释如下:
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// 获取xml文件名
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
// 获取xml文件路径
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// 添加控制器层注释,true表示显示控制器注释
options.IncludeXmlComments(xmlPath, true);
});
/// <summary>项目右键,选择属性,勾选“XML文档文件”,如下图所示:
/// 查看天气预报
/// </summary>
/// <param name="city">城市</param>
/// <returns>这里是返回结果</returns>
[HttpGet]
public IEnumerable<WeatherForecast> Get(string city)
{
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();
}
- 本文标题: NETCoreAPI接口之Swagger的安装
- 文章分类:【.NET/Web】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
- 上一篇:Vue如何生成EChart列表
- 下一篇: NetCore之Token通行证的生成