安装 Nuget 包
注册 Swagger
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //注册 Swagger services.AddSwaggerGen(sg => { sg.SwaggerDoc("refuge", new Swashbuckle.AspNetCore.Swagger.Info { Title = "我的第一个 Swagger", Version = "版本1" }); }); }
启用 Swagger
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //启用 Swagger app.UseSwagger(); app.UseSwaggerUI(s => { s.SwaggerEndpoint("/swagger/refuge/swagger.json", "My API 1.0.1");//注意,中间那段的名字 (refuge) 要和 上面 SwaggerDoc 方法定义的 名字 (refuge)一样 s.RoutePrefix = string.Empty; //默认值是 "swagger" ,需要这样请求:https://localhost:44384/swagger }); ...... }
修改 launchSetting.json 文件中指定的默认启动路径
{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:56872", "sslPort": 44384 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, //"launchUrl": "api/values", "launchUrl": "", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "SwashbuckleDemo2": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api/values", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
CTRL+F5 启动项目
下面,我们来丰富一下这个 Swagger
新建一个 PersonsController
编辑该项目属性:
给 Action 添加 XML 注释:
添加 Swagger 的XML注释提示功能
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //注册 Swagger services.AddSwaggerGen(sg => { sg.SwaggerDoc("refuge", new Swashbuckle.AspNetCore.Swagger.Info { Title = "我的第一个 Swagger", Version = "版本1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); sg.IncludeXmlComments(xmlPath); }); }
设置返回结果
Person 类如下:
/// <summary> /// 人 /// </summary> public class Person { /// <summary> /// 编号 /// </summary> public int Id { get; set; } /// <summary> /// 姓名 /// </summary> [Required(ErrorMessage = "姓名不能为空")] public string Name { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } }
-----------------------------------------------------------------------------------
下面是回复网友的评论:
/// <summary> /// 测试入参是实体,返回值也是实体 /// </summary> /// <param name="person">人</param> /// <returns></returns> [HttpPost] [ProducesResponseType(typeof(Person), 250)]//返个250给前端 public Person GetPerson([FromBody]Person person) { return person; }