增加接口文档
添加swagger包
打开程序包管理控制台,然后输入以下代码安装swagger包
Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc4
安装swagger
通过Nuget包管理器安装swagger
安装完毕以后可以在包中看到Swashbuckle.AspNetCore5.0
设置API输出XML文档文件
双击Properties,在打开的页面选择生成,按照红框内容配置xml文件输出
注册Swagger服务
打开XXX.api中Startup.cs文件,在ConfigureServices中注册Swagger服务
// 用来向容器中注册服务,注册好的服务可以在其他地方进行调用 | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
//数据库连接字符串string conn = Configuration.GetConnectionString("xxxDB"); | |
Models.XXXEntities.xxxContext.ConStr = conn; | |
//注册swagger服务,定义1个或者多个swagger文档 | |
services.AddSwaggerGen(s=> { | |
//设置swagger文档相关信息 | |
s.SwaggerDoc("v1", new OpenApiInfo | |
{ | |
Title = "xxxWebApi文档", | |
Description = "这是一个简单的NetCore WebApi项目", | |
Version = "v1.0" | |
}); | |
//获取xml注释文件的目录var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"; | |
var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile); | |
// 启用xml注释 | |
s.IncludeXmlComments(xmlPath); | |
}); | |
services.AddControllers(); | |
services.AddRouting(); | |
//services.AddDbContext<Models.XXXEntities.xxxContext>(options =>//{// options.UseSqlServer(conn);//}); | |
} |
SwaggerDoc是配置Swagger文档相关属性的地方,比如名称、描述、版本等
IncludeXmlComments 设置第二步中xml文档文件路径
打开XXX.api中Startup.cs文件,在Configure中启用Swagger服务
// 用来配置中间件管道,即如何响应http请求. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
else | |
{ | |
app.UseExceptionHandler("api/Error"); | |
} | |
app.UseRouting(); | |
app.UseAuthorization(); | |
//启用swagger中间件app.UseSwagger(opt=> { | |
//opt.RouteTemplate = "api/{controller=Home}/{action=Index}/{id?}"; | |
}); | |
//启用SwaggerUI中间件(htlm css js等),定义swagger json 入口app.UseSwaggerUI(s => { | |
s.SwaggerEndpoint("/swagger/v1/swagger.json", "xxxWebapi文档v1"); | |
//要在应用的根 (http://localhost:<port>/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串://s.RoutePrefix = string.Empty; | |
}); | |
app.UseEndpoints(endpoints => | |
{ | |
//endpoints.MapControllerRoute(// name: "default",// pattern: "api/{controller}/{action}/{id?}");endpoints.MapControllers(); | |
}); | |
} | |
如果想通过http://xxxx.com:<port>的方式访问Swagger文档则添加RoutePrefix = string.Empty;即可
解决No operations defined in spec!问题
一般来说按照上面的方式配置好就可以访问Swagger文档了,但是最后还是出了“No operations defined in spec!”的问题
问题原因:在前面我们将路由配置统一从Controller中去掉然后
endpoints.MapControllerRoute设置了路由模版,由于Swagger无法在Controller中找到[Route("api/[controller]/[action]")]和[ApiController]从而触发了“No operations defined in spec!”的问题。下图是我们注释的内容和增加的内容
解决方案
.将Startup.cs中Configure里的路由模版注释掉,改成endpoints.MapControllers();然后在Controller里添加路由模版,或者将Startup.cs中Configure里的路由模版注释掉,改成endpoints.MapControllers();,增加BaseController.cs并继承ControllerBase,然后在BaseController设置路由模版,让Controller继承BaseController
BaseController.cs代码
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Mvc; | |
namespace XXX.api | |
{ | |
/// <summary>/// 自定义路由模版/// 用于解决swagger文档No operations defined in spec!问题/// </summary> | |
[ | ]|
[ | ]|
public class BaseController : ControllerBase | |
{ | |
} | |
} |
解决CS1591警告
配置完Swagger以后出现了一个令人不爽的警告
双击Properties
找到生成,定位到错误和警告
新增取消显示警告1591
读取appsettings.json配置类
在appsettings.json文件中增加一个存放配置信息的参数AppSettings
{ | |
"Logging": { | |
"LogLevel": { | |
"Default": "Information", | |
"Microsoft": "Warning", | |
"Microsoft.Hosting.Lifetime": "Information" | |
} | |
}, | |
"AllowedHosts": "*", | |
//接口配置参数设置"AppSettings": { | |
//数据库连接字符串"xxxDB": "Server=127.0.0.1;User Id=用户id;Password=密码;Database=数据库名称;", | |
//接口是否需要签名"IsSign": "true", | |
//16位MD5签名key"Md5Key": "5ShiCeShiAAAAAAA" | |
} | |
} |
增加AppSettings.cs操作类
using Microsoft.Extensions.Configuration; | |
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace XXX.Common | |
{ | |
public class AppSettings | |
{ | |
private static IConfigurationSection appSection = null; | |
/// <summary>/// 获取配置文件/// </summary>/// <param name="key"></param>/// <returns></returns>public static string GetAppSeting(string key) | |
{ | |
if (appSection.GetSection(key)!=null) | |
{ | |
return appSection.GetSection(key).Value; | |
} | |
else | |
{ | |
return ""; | |
} | |
} | |
/// <summary>/// 设置配置文件/// </summary>/// <param name="section"></param>public static void SetAppSetting(IConfigurationSection section) | |
{ | |
appSection = section; | |
} | |
} | |
} |
修改Startup.cs
在Startup.cs中的Configure方法中获取appsettings.json值,代码如下
//从appsettings.json获取配置文件Common.AppSettings.SetAppSetting(Configuration.GetSection("AppSettings"));
使用
通过
Common.AppSettings.GetAppSeting("配置文件名")读取配置文件
示例:
从配置文件中读取连接字符串
打开XXXContext.cs在OnConfiguring方法中设置数据库连接字符串。
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){ | |
if (!optionsBuilder.IsConfigured) | |
{ | |
//通过配置文件操作类读取数据库连接字符串 | |
optionsBuilder.UseSqlServer(Common.AppSettings.GetAppSeting("xxxDB")); | |
} | |
} |