. NET Core uses swagger for API interface document management.

Source: Internet
Author: User

. NET Core uses swagger for API interface document management.

I. Problem background

With the development of technology, the current development model has switched more to the frontend and backend separation mode. In the process of frontend and backend development, the contact method has also become an API interface, however, in the current project, API management is often performed by manually writing documents. Each requirement change requires additional maintenance as long as it involves API changes, if a partner forgets to maintain the API, it will often cause continuous problems. How can we solve API communication problems more conveniently? Swagger provides us with a way to use. NET Core as an example because I am mainly engaged in the development of the. NET Core project.

2. What is Swagger?

Swagger can generate API information based on comments from different codes. swagger has a powerful community and supports various languages, there are many tools that can generate API documentation through the file generated by swagger

Iii. Use in. NET Core

To use. NET Core, first use nuget to reference Swashbuckle. AspNetCore, and add the following code to startup. cs:

  // This method gets called by the runtime. Use this method to add services to the container.  public void ConfigureServices(IServiceCollection services)  {   services.AddMvc();   services.AddSwaggerGen(c =>   {    c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" });    var basePath = PlatformServices.Default.Application.ApplicationBasePath;    var xmlPath = Path.Combine(basePath, "WebApplication2.xml");    c.IncludeXmlComments(xmlPath);   });   services.AddMvcCore().AddApiExplorer();  }  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  public void Configure(IApplicationBuilder app, IHostingEnvironment env)  {   if (env.IsDevelopment())   {    app.UseDeveloperExceptionPage();   }   app.UseMvcWithDefaultRoute();   app.UseSwagger(c =>   {   });   app.UseSwaggerUI(c =>   {    c.ShowExtensions();    c.ValidatorUrl(null);    c.SwaggerEndpoint("/swagger/v1/swagger.json", "test V1");   });  }

The above part is the code for loading swagger, which is located in startup. cs. The following is the controller code:

Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using Microsoft. aspNetCore. mvc; namespace WebApplication2.Controllers {// <summary> // test information /// </summary> [Route ("api/[controller]/[action]")] public class ValuesController: controller {// <summary> /// obtain all information /// </summary> /// <returns> </returns> [HttpGet] public IEnumerable <string> Get () {return new string [] {"value1", "value2 "};} /// <summary> /// obtain information by ID /// </summary> /// <param name = "id"> </param> /// <returns> </returns> // GET api/values/5 [HttpGet ("{id}")] public string Get (int id) {return "value ";} /// <summary> /// POST a data information // </summary> /// <param name = "value"> </param> // POST api /values [HttpPost] public void Post ([FromBody] string value) {}/// <summary> /// put data by ID /// </summary> /// <param name = "id"> </param> /// <param name = "value"> </param> // PUT api/values/5 [HttpPut ("{id}")] public void Put (int id, [FromBody] string value) {}/// <summary> /// DELETE data by ID /// </summary> /// <param name = "id"> </param>/DELETE api/values/5 [HttpDelete ("{id}")] public void Delete (int id) {}/// <summary> /// complex data operations /// </summary> /// <param name = "id"> </param> // DELETE api /values/5 [HttpPost] public namevalue test (namevalue _ info) {return _ info ;}} public class namevalue {// <summary> // name Information /// </summary> public String name {get; set ;} /// <summary> // value information // </summary> public String value {get; set ;}}}

Next, we need to hook up XML to generate a document in the production process,

Next we can run it. for debugging, enter http: // localhost: 50510/swagger/in the browser. The running effect of the port here is as follows:

As you can see, swagger captures the comments on the method and object, and displays the comments on swaggerui at a Glance. In addition, you can use the try it button for simple debugging, however, in a specific project, some client information may need to be brought to the service through the header, such as the token information, user Information (we need token in the header to be passed to the backend in the Project). How can this problem be solved? Let's take a look at the following practices:

// This method gets called by the runtime. Use this method to add services to the container.  public void ConfigureServices(IServiceCollection services)  {   services.AddMvc();   services.AddSwaggerGen(c =>   {    c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" });    var basePath = PlatformServices.Default.Application.ApplicationBasePath;    var xmlPath = Path.Combine(basePath, "WebApplication2.xml");    c.IncludeXmlComments(xmlPath);    c.OperationFilter<AddAuthTokenHeaderParameter>();   });   services.AddMvcCore().AddApiExplorer();  }
Public class AddAuthTokenHeaderParameter: IOperationFilter {public void Apply (Operation operation, OperationFilterContext context) {if (operation. parameters = null) {operation. parameters = new List <IParameter> ();} operation. parameters. add (new NonBodyParameter () {Name = "token", In = "header", Type = "string", Description = "token Authentication Information ", required = true });}}

We addedOperationFilter<AddAuthTokenHeaderParameter>() In this way, we can display the token header in swagger and debug (). The attribute context of apply of AddAuthTokenHeaderParameter contains various information about controller and action, can be used in combination with the actual situation

4. Integration with other API management tools

Swagger's powerful functions and the power of the community, many API management tools currently support YApi. Currently, we are using the YApi from where to open source, YApi supports importing JSON files generated by swagger. In addition to this tool, DOClever (Open Source) is also a good API management tool and also supports Swagger File Import (specific tool usage, you can go to their official website)


Source code download: demo address

V. Summary

Swagger is a good tool, and Swagger is becoming increasingly popular in front-end separate development. In the future development process, I think Swagger will play an increasingly important role, at present, our company's small projects are ready to start using swagger + yapi for API management. This article is also the result of taking the time to sort out API management, hoping to help you, there may be many shortcomings here. You are welcome to make a brick and hope to make progress together with everyone.

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.