One, background
With the popularity of the front and rear end of the separation mode, we need to write the interface to the back-end document provided to the front end, the front end can view our interface, and test and improve our development efficiency, reduce ineffective communication. In this case, by automatically generating code documentation, this demand came into being, swagger can automatically generate related api interface documentation through our code and comments, and can be viewed online, real-time updates, easy test to solve our real problems .
Second, create Webapi project, and add a reference to swagger
2.1 vs netcore2.2 of a project to create webapi
Project successfully created, Controllers folder is the interface to our api
2.2 add swagger package references
By nuget add swagger bag, you need to reference two packages, package name
Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Annotations
Third, create an interface and verify the generated documentation api
3.1 Project Startup.cs
Add Reference documentsusing Swashbuckle.AspNetCore.Swagger;
3.2 add the following code process ConfigureServices
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info() { Title = "Api", Version = "V1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});
3.3 Add method enabled in the Configure method
app.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
3.4 generate an XML file and verify
Validate the document automatically generated
our interface documentation has been automatically generated and may test
3.5 Controller and written verification
Create a controller PersonController, inherited from the Controller, the following code
[ApiController]
public class PersonController : Controller
{
/// <summary>
/// 获取人员信息
/// </summary>
///
/// <returns></returns>
[HttpGet]
[Route("api/Person/Index")]
public List<Person> Index()
{
return new List<Person>()
{
new Person() {Age = 10, Name = "张三"},
new Person() {Age = 20, Name = "李四"},
};
}
}
Until then open the document and view swagger
you can also see our comments in the document shows.
IV Summary
swagger是一个非常强大的插件,可以帮助我们快速生成api文档,给前后端分离带来了极大的方便。
参考文档:
1.https://github.com/domaindrivendev/Swashbuckle.AspNetCore
2.https://www.cnblogs.com/viter/p/10053660.html
3.https://www.cnblogs.com/yilezhu/p/9241261.html