asp. Principle analysis of integrating swagger UI with. Net core

Time:2022-6-14

What is swagger?

Before we talk about swagger, let’s talk about the OpenAPI specification.

OpenAPI is a language independent specification used to describe the functions of the restapis interface. The description of the restapis interface includes: interface parameter information, interface return value information, API function description, request path, etc.

Here we say that OpenAPI is just a specification. Since it is a specification, there must be corresponding implementation. Swagger is one of the tools that implements the open API specification.

. Net is the web API, and Net also has corresponding swagger implementation for web APIs, mainly including:SwashbuckleandNSwag, this article mainly explains how to integrate swaggerui into asp Net core project, and quickly generate asp Net web API interface document.

Basic principle analysis

Before getting to the point, let’s take a look at the effect of the rapid integration of swagger UI in my web API sample site, and remember the two keywords swaggerui interface and OpenAPI JSON information mentioned below, because these two words will be mentioned many times later.

The swaggerui interface is shown in the following figure:

The OpenAPI JSON information is as follows (the JSON information describes all interfaces of the web API and is generated according to the OpenAPI specification):

The general principle is that when we enter: http://localhost:5000/swagger/index.html Request the swaggerui page. After the swaggerui middleware intercepts the request, it reads the content of the built-in swaggerui page and responds to the browser. The browser then initiates an asynchronous request to request OpenAPI JSON information, and then generates all the interface information in the first figure above according to the OpenAPI JSON information. We can see the request through the browser’s developer tools.

OK, after understanding the basic principle of swaggerui, let’s explain how to quickly integrate swaggerui into the web API project.

Install the nuget package related to swagger

Install the nuget package in the project that needs to integrate swagger: swashbuckle AspNetCore

Inject swaggerapi document generation service and add swaggerui response Middleware

Open startup CS file, modify the configuservice method, and add the API document generation service to the dependency injection container.

public void ConfigureServices(IServiceCollection services)
        {
            //Here, the OpenAPI JSON information generation service is added to the dependency injection container to generate the corresponding OpenAPI JSON information according to the definition of the web API.
            services.AddSwaggerGen();
            services.AddControllersWithViews();
        }

Modify startup CS, add the swagger UI request interception middleware and OpenAPI JSON information request interception middleware to the list of request middleware pipelines.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            //Useswagger adds a middleware, which mainly intercepts the HTTP request for OpenAPI JSON information sent from the browser and returns the webapi description information to swaggerui. In the above figure, we can see that the default HTTP address for requesting OpenAPI JSON information is: http://localhost:5000/swagger/v1/swagger.json
            app.UseSwagger();
            
            //Useswaggerui adds a middleware, which is mainly used to intercept the access request of swaggerui interface and dynamically generate the interface list according to the OpenAPI JSON information. In the above basic principle description, the HTTP address of the default request swaggerui interface is: http://localhost:5000/swagger/index.html
            app.UseSwaggerUI((options) =>
            {
                //The swaggerendpoint method is used to tell swaggerui which address to request to obtain OpenAPI JSON information. We will explain how to customize this path later.
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

OK, so far, swaggerui has been integrated into our webapi project. If nothing unexpected happens, you can normally see the effect diagram mentioned in the basic principle analysis above. Is it very simple? Let’s explain some more in-depth usage.

How to customize the OpenAPI JSON information request HTTP address?

The default OpenAPI JSON information request address is: /swagger/v1/swagger JSON, if we want to change to another address, for example: /blogapis/v1/swagger How does JSON work?

First, configure the middleware that intercepts swaggerui interface requests, and tell swaggerui which address to request OpenAPI JSON information from.

app.UseSwaggerUI((options) =>
{
      //options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
      //Here, tell swaggerui to start from /bogapis/v1/swagger JSON to get OpenAPI JSON information.
        options.SwaggerEndpoint("/BlogApis/v1/swagger.json", "BlogApis");
});

Then configure the middleware that intercepts OpenAPI JSON information, and redefine the request path format of OpenAPI JSON information, as follows:

app.UseSwagger(swaggerOptions =>
{
       //Tell the OpenAPI JSON information request interception middleware to return the OpenAPI JSON information when receiving the request in the following format
       //Note: the path must contain: {documentname}. Swagger middleware extracts the API document name from the placeholder position of {documentname} in the request path to display the API documents grouped under the document name 
       //All API information.
       swaggerOptions.RouteTemplate = "/BlogApis/{documentName}/swagger.json";
});

By the way, by looking at the swagger source code, we can see that the default OpenAPI JSON parsing route is swagger/{documentname}/swagger JSON, which is why we must use /swagger/v1/swagger JSON format to request OpenAPI JSON information.

How do I group and present the specified APIs in swaggerui?

We mentioned above that the {documentname} parameter must be included in the resolution route of OpenAPI JSON request address, such as: /blogapis/{documentname}/swagger JSON. At the same time, it is mentioned that the OpenAPI JSON information request address corresponds to this route one by one. For example, the OpenAPI JSON information request address defined above is: /blogapis/v1/swagger JSON, when the browser accesses the swaggerui page and requests /blogapis/v1/swagger JSON address, according to the routing template: /blogapis/{documentname}/swagger JSON extracts V1 from the second paragraph of the OpenAPI JSON request address as the API document name, and then loads all API information with the group name V1 or undefined group name by default and displays it. How can we display the API in groups through the documentname?

Open startup CS, find the configureservices method and add the following code:

services.AddSwaggerGen(options =>
            {
                //Here, we divide the user related APIs into a group. The user here is the documentname
                options.SwaggerDoc("User", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "user management",
                    Version = "1.0"
                });
                //Here we will divide the article management related APIs into a group.
                options.SwaggerDoc("Post", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "article management",
                    Version = "1.0"
                });
                //The following is where to get parameter comments, return values and other information for setting all web APIs in swaggerui.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });

Find the configure method and configure it as follows:

app.UseSwaggerUI((options) =>
            {
                //options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                //options.SwaggerEndpoint("/BlogApis/v1/swagger.json", "BlogApis");

                //Define the OpenAPI JSON information request path of user management related APIs.
                options.SwaggerEndpoint("/BlogApis/User/swagger.json", "UserManagerApis");
                //Define the OpenAPI JSON information request path of article management related APIs.
                options.SwaggerEndpoint("/BlogApis/User/swagger.json", "PostManagerApis");
            });

Add [apiexplorersettings] attribute on usercontroller and postcontroller respectively, and set the group name

[Route("api/[controller]"), ApiExplorerSettings(GroupName = "User")]
    [ApiController]
    public class UserController : ControllerBase
    {
        /// <summary>
        ///User login
        /// </summary>
        ///<param name= "username" > username </param>
        ///<param name= "password" > password </param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(200, Type = typeof(UserInfo))]
        public UserInfo Login([FromForm] string userName, [FromForm] string password)
        {
            if (userName == "chenxin" && password == "123456")
            {
                return new UserInfo() { UserName = "chenxin", Age = 31 };
            }
            return null;
        }

        [HttpGet]
        public List<UserInfo> GetAllUsers()
        {
            return new List<UserInfo>()
            {
                new UserInfo()
                {
                    UserName="chenxin",
                    Age=31
                },
                new UserInfo()
                {
                    UserName="zhangsan",
                    Age=35
                }
            };
        }
[Route("api/{controller}")]
    [ApiExplorerSettings(GroupName = "Post")]
    public class PostController : ControllerBase
    {
        /// <summary>
        ///Get all articles
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<Post> GetAllPosts()
        {
            return new List<Post> { new Post()
            {
                Title= "test article",
                Content= "test content..."
            } };
        }
    }
    public class Post
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime PublishTime { get; set; } = DateTime.Now;
    }

After following the above steps, we can see that API grouping has been implemented.

Well, the question arises. Why can we find API information without defining any document name using swaggerdoc method by default? In fact, swagger middleware adds a document named V1 to us by default.

How to customize the request path of swaggerui?

If you do not want to enter swagger/index HTML to access swaggerui. For example, to change to /blogapisdocs, open startup CS find the configure method and add the following code:

app.UseSwaggerUI((options) =>
            {
                //options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                //options.SwaggerEndpoint("/BlogApis/v1/swagger.json", "BlogApis");

                //Define the OpenAPI JSON information request path of user management related APIs.
                options.SwaggerEndpoint("/BlogApis/User/swagger.json", "UserManagerApis");
                //Define the OpenAPI JSON information request path of article management related APIs.
                options.SwaggerEndpoint("/BlogApis/User/swagger.json", "PostManagerApis");

                //Here, we tell swaggerui to request the interception middleware. When we receive the request of /blogapisdocs sent by the browser, we will return to the swaggerui page.
                options.RoutePrefix = "BlogApisDocs";
            });

How to automatically display API method annotations and parameter annotations through swaggerui?

Open startup CS find the configureservices method and add the following code:

services.AddSwaggerGen(options =>
            {
                //Here we divide the user related APIs into a group.
                options.SwaggerDoc("User", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "user management",
                    Version = "1.0"
                });
                //Here we will divide the article management related APIs into a group.
                options.SwaggerDoc("Post", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title = "article management",
                    Version = "1.0"
                });
                //The following is where to get parameter comments, return values and other information for setting all web APIs in swaggerui.
                //This means to read the annotation information of the API from the specified XML configuration file under the root directory of the site.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });

Then you need to set the webapi project to automatically generate an XML file describing API information when generating the project, and you need to set the generated XML configuration file swaggerdemo XML is set to always copy to the output directory:

Well, that’s all for the basic usage. This article mainly explains how to group APIs. Here is just an example of grouping according to API functions. In fact, in actual development, the method of grouping can be flexibly defined according to requirements, such as grouping according to API version.

If you have any questions during reading this article, you are welcome to my personal blog:http://www.lovecoding.com.cnLeave a message and reply in time!

This is about asp This is the end of the article on integrating swagger UI with asp Net core integrated swagger UI content please search for previous articles of developeppaer or continue to browse the following related articles. I hope you will support developeppaer in the future!

Recommended Today

Dubbo integrates zookeeper/redis/multicast as the registration center

Dubbo integrated series 1、 Zookeeper 1. Preparation 1. Installing zookeeper 2. Dubbo installation 2. Project construction 1. first create a parent project Dubbo parent, and then import the dependency 2. Create a public API interface project: common API, and then create a helloservice interface 3. Create a service provider project: server provider, and then introduce […]