. netCore3.0 + WebApi + Vue2.0 project construction - use of and Swagger

Keywords: Vue.js .NET microsoft

1, What is Swagger

Swagger is a normative and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The overall goal is to make the client and file system update at the same speed as the server. The file's methods, parameters and models are tightly integrated into the server-side code, allowing the API to keep pace all the time.
Function: interface document is automatically generated online and function test is performed

2, Why use Swagger

I believe that both front-end and back-end development have been more or less tortured by interface documents. The front end often complains that the interface documents provided by the back end are inconsistent with the actual situation. The back-end feels that writing and maintaining interface documents will consume a lot of energy and often have no time to update. In fact, whether the front end calls the back end or the back end calls the back end, it is expected to have a good interface document. However, for programmers, this interface document is just like comments. They often complain that the code written by others does not write comments. However, when they write their own code, the most annoying thing is to write comments. Therefore, it is not enough to regulate everyone only through coercion. With the passage of time, version iteration and interface documents often can't keep up with the code.

3, Configure Swagger service

1. Import Nuget package

Using NuGet package to add assembly application

Right click dependencies in the project -- > manage NuGet packages -- > Browse

Once the installation is complete, you can view it in dependencies

2. Configure services

Open Startup.cs and edit the ConfigureServices method

public string ApiName { get; set; } = "WebApi"; //It is defined as a global variable for easy modification

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Swagger
            services.AddSwaggerGen(c => 
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = $"{ApiName} Interface documentation-- .netCore3.0",
                    Description = $"{ApiName} Framework description document"

                });
                c.OrderActionsBy(o => o.RelativePath);
            });
        }

3. Start Http Middleware

Open Startup.cs and edit the Configure method

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"{ApiName} v1");

                // The path configuration is set to null, which means that the file is accessed directly in the root domain name (localhost:8001),
                // Note that localhost:8001/swagger cannot be accessed. Go to launchSettings.json to remove the launchUrl,
                // If you want to change a path, just write the name directly, such as c.RoutePrefix = "doc";
                c.RoutePrefix = "";
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

4. View effect

Open the launchSettings.json file, delete the red part, set the launchUrl to empty, or delete it.

There are two methods for debugging. net core: IIS debugging and the project's own Kestrel web application mode. Here, delete IIS debugging from launchsettings.json and use Kestrel web


Press F5 to view the debugging results

5. Add comments

Right click the project name = > attribute = > generate, and check the "xml document file" under "output", and the system will generate one by default. Of course, as the old rule, you can also name it yourself:

Here I use the relative path, which can be directly generated to the bin folder of the api layer

If you don't want to annotate every method like this, you can configure it like this (configure the current project, ignore the warning, and remember to add a semicolon; 1591):
Open Startup.cs and edit the ConfigureServices method

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Swagger
            services.AddSwaggerGen(c => 
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = $"{ApiName} Interface documentation-- .netCore3.0",
                    Description = $"{ApiName} Framework description document"

                });
                c.OrderActionsBy(o => o.RelativePath);

                //configuration file
                var xmlPath = Path.Combine(AppContext.BaseDirectory, "MyNewTest.Core.xml");
                c.IncludeXmlComments(xmlPath, true);//The default second parameter is false. This is the comment of the controller. Remember to modify it
            });
        }

Adding comments to the Model layer is the same as the above operation, only one more sentence of code is required

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Swagger
            services.AddSwaggerGen(c => 
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = $"{ApiName} Interface documentation-- .netCore3.0",
                    Description = $"{ApiName} Framework description document"

                });
                c.OrderActionsBy(o => o.RelativePath);

                //configuration file
                var xmlPath = Path.Combine(AppContext.BaseDirectory, "MyNewTest.Core.xml");
                c.IncludeXmlComments(xmlPath, true);//The default second parameter is false. This is the comment of the controller. Remember to modify it

                //model layer
                var xmlModelPath = Path.Combine(AppContext.BaseDirectory, "MyNewTest.Model.xml");
                c.IncludeXmlComments(xmlModelPath);
            });
        }


6. Hide interface
If you don't want to display some interfaces, add features directly on the controller or action

[ApiExplorerSettings(IgnoreApi = true)]

Posted by robgudgeon on Sat, 06 Nov 2021 09:34:48 -0700