上一章快速使用SqlSugar搭建了netcore api项目,我的第一个netcore2.2 api项目搭建(一)
这一章实现目标二:api使用Swagger,实现api文档管理
效果图:第一张收缩,第二张展开,共有2个控制器:values和Account;控制器有注释,api有注释,实体有注释
1.1添加swagger引用
nuget搜索:Swashbuckle.AspNetCore,安装
1.2在startup中注册swagger
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //添加api管理 // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { //Version = "v1", Title = "MyFirst API",//" API", //Description = "", //TermsOfService = "None", //Contact = new Contact //{ // Name = "", // Email = string.Empty, // Url = "" //}, //License = new License //{ // Name = "Use under LICX", // Url = "" //} }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath, true); xmlPath = Path.Combine(AppContext.BaseDirectory, "JH.OPEMR.Model.xml"); options.IncludeXmlComments(xmlPath, true); }); }
注意这段:
这段代码是添加注释,如果有多个文件注释,只要逐个添加就好了,不建议将xml合并,并且这个需要项目生成相应xml
1.3在Configure中启用swagger
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //启用Swagger // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseMvc(); }
F5运行之前将启动页改成swagger
F5运行
ok,swagger添加完成。
but,我尝试添加了一个GetUsers方法。。。
swagger失败,该死api路由,很不好理解,还是改成这样吧
F5,变成这样,直观多了。。。
至此,swagger添加完毕