Asp.net core WebApi use Swagger to generate a Help page instance.
Our team has been running recently. net core transformation, web development is evolving towards the technical architecture of front-end and back-end separation. Our backend mainly uses asp.net core webapi for development, this problem exists in every debugging and communication with front-end personnel. When I read the official documents of Microsoft asp.net core, I found swagger. Then this technology is introduced into the actual project. The process of testing self-written APIS is greatly simplified. Front-end engineers can also test some front-end code based on the swagger help pages provided by us, this greatly improves the development efficiency at the front and back ends. Next I will explain how to introduce swagger in asp.net core webapi step by step using my own real launch project. (You can also refer to Microsoft official documentation: https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger)
1. Introduce the swagger Nuget package
Right-click wepapi project dependencies and Click Manage Nuget packages, for example:
On the NuGet package management page, enter Swashbuckle. AspNetCore. The current package version is 1.0.0. Click to install the package.
After the installation is complete, you need to configure it in the Startup. cs file in the project.
Ii. Configure Swagger
Open the Startup. cs file and add the following code in the ConfigureServices method:
Services. addSwaggerGen (c => {c. swaggerDoc ("v1", new Info {Version = "v1", Title = "TwBusManagement interface documentation", Description = "RESTful API for TwBusManagement", TermsOfService = "None ", contact = new Contact {Name = "Alvin_Su", Email = "asdasdasd@outlook.com", Url = ""}); // Set the comments path for the swagger json and ui. var basePath = PlatformServices. default. application. applicationBasePath; var xmlPath = Path. combine (basePath, "twbusapi. xml "); c. includeXmlComments (xmlPath); // c. operationFilter <HttpHeaderOperation> (); // Add the httpHeader parameter });
Note that the last three lines of the above Code are the generated address and file name of the xml api Description document, which must be configured in the properties of the project. For example:
In addition, to disable warning, add code 1591 to filter out alarm information for some class names without comments.
Finally, add the following code in the Configure method. Note that the following code must be added before app. UseMvc:
// Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "TwBusManagement API V1"); c.ShowRequestHeaders(); });
After the above configuration, you can use the help page generated by Swagger. After running the project, add the suffix/swagger to the browser address to jump to the Help Page:
Of course, it is too troublesome for our developers to manually enter the address to jump to the Help Page during the development project process. We can use visual studio to redirect, such:
Open the launchSettings. json file and set the webapi project startup path to swagger. In this way, the swagger help page is automatically displayed for each debugging and running project.
Iii. Some advanced Swagger usage
Swagger is very powerful, not only for some help page information, but also for api debugging. In this way, you do not need to use third-party tools such as postman for webapi debugging. After swagger is configured, you can enter some http header information, such as permission authentication information. The following describes the specific configuration.
First, we need to create a new class HttpHeaderOperation to inherit the IOperationFilter interface. This interface needs to introduce the namespace: Swashbuckle. AspNetCore. SwaggerGen. The implementation method of the interface is as follows:
Public class HttpHeaderOperation: IOperationFilter {public void Apply (Operation operation, OperationFilterContext context) {if (operation. parameters = null) {operation. parameters = new List <IParameter> ();} var actionAttrs = context. apide.pdf. actionAttributes (); var isAuthorized = actionAttrs. any (a =>. getType () = typeof (AuthorizeAttribute); if (isAuthorized = false) // The provided action does not have the permission attribute tag. Check whether the controller has {var controllerAttrs = context. apide.pdf. controllerAttributes (); isAuthorized = controllerAttrs. any (a =>. getType () = typeof (AuthorizeAttribute);} var isAllowAnonymous = actionAttrs. any (a =>. getType () = typeof (AllowAnonymousAttribute); if (isAuthorized & isAllowAnonymous = false) {operation. parameters. add (new NonBodyParameter () {Name = "Authorization", // Add the Authorization header parameter In = "header", Type = "string", Required = false });}}}
In the ConfigureServices method in Startup. cs, locate the previous AddSwaggerGen code segment and add the following code at the end:
C. operationFilter <HttpHeaderOperation> () services. addSwaggerGen (c => {c. swaggerDoc ("v1", new Info {Version = "v1", Title = "TwBusManagement interface documentation", Description = "RESTful API for TwBusManagement", TermsOfService = "None ", contact = new Contact {Name = "Alvin_Su", Email = "alvin_su@outlook.com", Url = ""}); // Set the comments path for the swagger json and ui. var basePath = PlatformServices. default. application. applicationBasePath; var xmlPath = Path. combine (basePath, "twbusapi. xml "); c. includeXmlComments (xmlPath); c. operationFilter <HttpHeaderOperation> (); // Add the httpHeader parameter });
In this way, after allowing the webapi project, you can enter the Authorization Header parameter. For example: