如何建 .netcore webapi 项目这个就不说了,这个都没有没必要看下去。
netcore 2.2
1.Nuget Packages安装,使用程序包管理器控制台,安装命令:Install-Package Swashbuckle.AspNetCore -Pre
或者搜索安装 Swashbuckle.AspNetCore.Swagger
2.生成项目xml文档,多项目的情况下
3.配置Startup.cs。为了直观,我把整个类贴这里了,具体功能看代码注释,自己取舍。
1 using System; 2 using System.Net.Http; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Threading.Tasks; 6 using Microsoft.AspNetCore.Builder; 7 using Microsoft.AspNetCore.Hosting; 8 using Microsoft.Extensions.Configuration; 9 using Microsoft.Extensions.DependencyInjection;10 using Microsoft.Extensions.Logging;11 using Microsoft.Extensions.Options;12 using Swashbuckle.AspNetCore.Swagger;13 using Newtonsoft.Json;14 using Newtonsoft.Json.Serialization;15 using Microsoft.Extensions.PlatformAbstractions;16 using System.IO;17 18 namespace CVOL.Api.Test19 {20 public class Startup21 {22 public Startup(IConfiguration configuration)23 {24 Configuration = configuration;25 }26 27 public IConfiguration Configuration { get; }28 29 // This method gets called by the runtime. Use this method to add services to the container.30 public void ConfigureServices(IServiceCollection services)31 {32 //services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList"));33 services.AddMvc().AddJsonOptions(options =>34 {35 //忽略循环引用36 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;37 //不使用驼峰样式的key38 options.SerializerSettings.ContractResolver = new DefaultContractResolver();39 //设置时间格式40 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff";41 });42 43 // Register the Swagger generator, defining one or more Swagger documents。info的参数不是必填的。那个版本号尽量不要改,可能会出错44 services.AddSwaggerGen(options =>45 {46 options.SwaggerDoc("v1", new Info47 {48 Title = "我的测试接口",49 Version = "测试版本1.0",50 Description = "这是个简单测试接口 ASP.NET Core Web API",51 TermsOfService = "哈哈哈",52 Contact = new Contact { Name = "清风神剑", Email = "xx@qq.com", Url = "" }53 });54 var basePath = AppContext.BaseDirectory;55 //Set the comments path for the swagger json and ui.只有一个的话不需要这种循环的方式 56 string[] arr = new string[] { "CVOL.API.Test.xml", "CVOL.Core.Model.xml" };57 foreach (var item in arr)58 {59 var xmlPath = Path.Combine(basePath, item);60 options.IncludeXmlComments(xmlPath);61 }62 63 64 });65 66 67 }68 69 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.70 public void Configure(IApplicationBuilder app, IHostingEnvironment env)71 {72 app.UseSwagger();73 74 // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.75 app.UseSwaggerUI(c =>76 {77 c.SwaggerEndpoint("v1/swagger.json", "测试接口 V1");78 });79 app.UseMvcWithDefaultRoute();80 }81 }82 }
4.设置默认启动项目,不设置的话要打开http://localhost:port/swagger/
5.写个测试代码吧。
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using CVOL.Api.Test.Models;using CVOL.Core.Model;namespace CVOL.Api.Test.Controllers{ ////// 测试控制器 /// [Route("api/[controller]")] public class TestController : Controller { ////// 获得字符串 /// /// 写入的字符串 ///获得字符串 [HttpGet] public string GetStr(string str) { return "这是获得的字符串:" + str; } ////// 获取时间 /// ///返回时间 [HttpGet] [Route("GetDates")] public DateTime GetDates() { return DateTime.Now; } ////// 获取类 /// /// 输入名字 ///返回类 [HttpGet] [Route("GetTry")] public TodoItem GetTry(string name) { return new TodoItem { IsComplete = false, Name = name }; } ////// 插入 /// /// 类 ///[HttpPost] [Route("InsetNew")] public TodoItem InsetNew(TodoItem item) { return item; } /// /// 获取 /// /// 类 ///返回 [HttpPost] [Route("GetNew")] public NewTestClass GetNew(NewTestClass nt) { return nt; } }}
上面每个方法的2个标签必填,否则swagger打不开。
最后来看看效果。
样子还是不错的。另外推荐一款测试工具 SOAPUI,挺好用的。