1.新建一个WebApi空项目
2.新建一个Person实体类:
public class Person
{
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
3.新建一个PersonAPI控制器(PersonController)
public class PersonController : ApiController { /// <summary> /// 根据ID获取单个人的详细信息 /// </summary> /// <param name="id">人员ID</param> /// <returns></returns> [HttpGet, Route("person/GetPerson")] public Person GetPerson(int id) { return new Person { ID = id, UserName = "张三", Password = "admin888" }; } /// <summary> /// 获取人员列表信息 /// </summary> /// <returns></returns> [HttpGet, Route("person/GetPersons")] public List<Person> GetPersons() { List<Person> list = new List<Person> { new Person{ ID = 3, UserName = "张三", Password = "admin888"}, new Person{ ID = 4, UserName = "李四", Password = "admin888"}, new Person{ ID = 5, UserName = "王五", Password = "admin888"}, new Person{ ID = 6, UserName = "小七", Password = "admin888"} }; return list; } /// <summary> /// 添加人员 /// </summary> /// <param name="product"></param> /// <returns></returns> [HttpPost, Route("person/add")] public int AddProduct(Person person) { throw new NotImplementedException(); } /// <summary> /// 更新删除人员 /// </summary> /// <param name="personId"></param> /// <param name="person"></param> [HttpPost, Route("person/update")] public void UpdatePerson(int personId, Person person) { throw new NotImplementedException(); } /// <summary> /// 删除人员 /// </summary> /// <param name="personId"></param> [HttpDelete, Route("product/delete")] public void DeletePerson(int personId) { throw new NotImplementedException(); } }
4.通过NuGet程序包安装swashbuckle程序包
5.安装后App_Start目录下会生成一个SwaggerConfig.cs文件,修改此文件:
取消c.IncludeXmlComments(GetXmlCommentsPath())的注释,同时添加GetXmlCommentsPath函数
private static string GetXmlCommentsPath() { return string.Format(@"{0}inXXXX.XML", AppDomain.CurrentDomain.BaseDirectory); }
其中"XXX.xml"为"你的项目名.xml"
6.右键项目-属性-生成,勾选"xml文档文件"
7.好了,生成好之后通过http://主机/swagger/ui/index#/ 地址就可以访问了