Install Swagger related packages
Open your C# project solution, in Visual Studio, right-click on the project name and select "Manage NuGet Packages".
In NuGet Package Manager, search for the following packages and install:
- : This is the main library for Swagger for Core, which includes the functions of generating Swagger documentation and providing Swagger UI.
- : Provides model definitions of OpenAPI specifications, and these models will be used to generate Swagger documents.
Configure Swagger Service
- On the project
In the file, find
ConfigureServices
Method, add the following code to configure the Swagger service:
using ; using ; public void ConfigureServices(IServiceCollection services) { // Other service configuration... // Add Swagger generator service (c => { // Define Swagger document information ("v1", new OpenApiInfo { Version = "v1", Title = "Your API Title", Description = "Your API description", TermsOfService = new Uri("/terms"), Contact = new OpenApiContact { Name = "Contact Name", Email = "contact@", Url = new Uri("/contact") }, License = new OpenApiLicense { Name = "License Name", Url = new Uri("/license") } }); // Configure the XML comment file path to display method comments and other information in Swagger documents var xmlFile = $"{().GetName().Name}.xml"; var xmlPath = (, xmlFile); (xmlPath); // If your API has security mechanisms such as authentication, you can configure it here ("Bearer", new OpenApiSecurityScheme { In = , Description = "Please enter JWT with Bearer prefix", Name = "Authorization", Type = }); (new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = , Id = "Bearer" } }, new string[] {} } }); }); }
- In the above code, first pass
AddSwaggerGen
The method adds the Swagger generator service and defines the basic information of the Swagger document, such as version, title, description, etc. Then configure the path of the XML comment file, so that Swagger will generate more detailed document content based on the XML comment. Finally, the authentication mechanism of the Bearer token is configured.
Enable Swagger Middleware
- exist
Filed
Configure
In the method, add the following code to enable Swagger middleware:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Other middleware configurations... // Enable Swagger (); // Enable Swagger UI and specify the route of Swagger JSON documents (c => { ("/swagger/v1/", "Your API v1"); // If necessary, you can configure other options of the Swagger UI, such as document expansion depth, etc. (); }); }
- This code is first used
UseSwagger
Middleware to generate Swagger JSON documents and then useUseSwaggerUI
Middleware provides the Swagger UI interface, which is convenient for users to view and test the API. passSwaggerEndpoint
The method specifies the route of the Swagger JSON document and the document name displayed in the Swagger UI.
Verify that Swagger is configured successfully
- Run your C# project and type in the browser
http://localhost:port/swagger
,inport
It is the port number for your project to run. - If everything is configured correctly, you should be able to see the Swagger UI interface, which lists all API endpoints in your project, and you can view details for each endpoint and test it.
Add comments and descriptions to specific APIs
- To make the Swagger documentation more detailed and accurate, XML comments can be added to the controller's method and model classes.
- For example:
/// <summary> /// Get user information/// </summary> /// <param name="id">User ID</param>/// <returns>User Information Object</returns>[HttpGet("{id}")] public IActionResult GetUser(int id) { // Method implementation}
- In this way, you can see more detailed API instructions in the Swagger UI.
When configuring Swagger service, adding security definitions allows you to specify various security mechanisms for the API, such as JWT authentication, API key authentication, etc. The following is an example of how to add security definitions using common JWT authentication and API key authentication:
JWT certification security definition
Add namespace references
existAt the top of the file, add the following namespace reference:
using ; using ;
Configure Swagger security definition in ConfigureServices method
existFiled
ConfigureServices
In the method, find(c => {})
Code block, where the following code is added:
// Add Swagger generator service(c => { // Other Swagger configurations... // Add JWT Bearer security definition ("Bearer", new OpenApiSecurityScheme { // Define the type of security mechanism as API key Type = , // Instruct the key is located in the request header In = , // The field name in the request header used to pass the JWT token Name = "Authorization", // The description of this security definition will be displayed to the user in the Swagger UI Description = "Please enter a JWT token with Bearer prefix" }); // Add security requirements, specify that the API defined by Bearer security requires authentication (new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { // Reference the Bearer security definition defined earlier Reference = new OpenApiReference { Type = , Id = "Bearer" } }, // Here you can specify some additional scope or permissions, and you can leave an empty array if you don't need it new string[] { } } }); });
The above code is first usedAddSecurityDefinition
The method has been added with the nameBearer
The security definition of the security mechanism is specified as the API key, located in the request headerAuthorization
and a description is given in the field. Then useAddSecurityRequirement
Method specified useBearer
Security-defined APIs require authentication.
API key authentication security definition
Add namespace references
Also inAt the top of the file, add the same namespace reference as when JWT authentication security definition:
using ; using ;
Configure Swagger security definition in ConfigureServices method
existFiled
ConfigureServices
In the method, find(c => {})
Code block, where the following code is added:
// Add Swagger generator service(c => { // Other Swagger configurations... // Add API key security definition ("ApiKey", new OpenApiSecurityScheme { // Define the type of security mechanism as API key Type = , // Instruct the key is located in the request header In = , // The field name in the request header used to pass the API key Name = "X-Api-Key", // The description of this security definition will be displayed to the user in the Swagger UI Description = "Please enter your API key" }); // Add security requirements, specify that the API defined using ApiKey security requires a valid API key. (new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { // Reference the ApiKey security definition defined earlier Reference = new OpenApiReference { Type = , Id = "ApiKey" } }, // Here you can specify some additional scope or permissions, and you can leave an empty array if you don't need it new string[] { } } }); });
The above code has been added with the nameApiKey
The security definition of the specified security mechanism is the API key, located in the request headerX - Api - Key
and a description is given in the field. At the same time, safety requirements have been added to ensure useApiKey
Security-defined APIs need to provide valid API keys when invoking.
API testing and debugging can be conveniently performed in Swagger. The following are the specific steps:
Preparation
- Make sure that Swagger has been successfully referenced and configured in the project, and that the project can run normally and the Swagger UI can be accessed normally.
Test API
Access the Swagger UI: After starting the project, enter the address of the Swagger UI in the browser, such ashttp://localhost:port/swagger
,inport
It is the port number for the project to run. Entering the Swagger UI interface, you will see a list of all exposed APIs in the project, each API is displayed with its defined HTTP methods (such as GET, POST, PUT, DELETE, etc.) and path.
Select the API to test: Find the API endpoint you want to test in the Swagger UI. Each API endpoint has corresponding description and parameter information.
Fill in the parameters: For APIs that require parameters, fill in the corresponding value in the parameter input area provided by Swagger UI. Parameter types may include path parameters, query parameters, request body parameters, etc.
-
Path parameters: Usually in braces in API path
{}
Indicates that directly enter parameter values in the corresponding input box. -
Query parameters: Generally, the question mark is placed behind the path
?
Start with multiple parameters&
Connect, there will be a special input box in the Swagger UI for filling in the name and value of the query parameters. - Request body parameters: For APIs such as POST and PUT that need to send request body, there is usually a dedicated area in the Swagger UI for inputting request body data in JSON or other formats. The correct request body structure can be constructed according to the requirements of the API and filled in the corresponding value.
Set request header: If the API requires specific request header information, such asAuthorization
、Content-Type
etc. Find the "request header" or similar area in the Swagger UI and add the corresponding request header name and value. For example, if the API requires authentication, you may need to add it hereAuthorization
header and set its value to a valid token.
Perform a test: After filling in the parameters and request headers, click the "Execute" or "Try!" button next to the API endpoint, and Swagger will send the request to the backend API.
View the response results: After sending a request, the Swagger UI will display the API's response results, including the response status code, response header and response body. You can judge whether the API is working properly and whether the returned data meets expectations based on the response information.
Debug API
- View request details: If the test results do not meet expectations, you can view the requested details to help debug. In the Swagger UI, there is usually a "View Request" or similar button. After clicking, you can view the sent complete request information, including the request URL, method, parameters, request header, and request body, etc., to ensure that the content of the request is consistent with the expectations.
- Check the response status code: Determine the processing status of the request based on the response status code. Common status codes such as 200 indicate successful request, 400 indicates an error in the client's request, 401 indicates unauthorized, 500 indicates internal error in the server, etc. According to different status codes, the direction of the problem can be initially determined.
- Analyze the response body: Carefully view the information in the response body, which may contain error messages, debug information, or other useful tips. If the response body is in JSON format, you can use the JSON formatting tool to view its structure and content more clearly.
- Combined with backend logs: When debugging the API, it is very helpful to view the logs of the backend server. The backend log can provide more detailed information, such as the request processing process, the occurrence of exceptions, etc. Based on the information in the log, specific code locations can be located to further analyze and solve the problem.
- Modify the request and retest: According to the analysis results, modify the request parameters, request headers or request bodies, and then click the "Execute" button again to resend the request to observe whether the response results have improved. By constantly modifying and testing, gradually debug the API until the expected results are achieved.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.