As a back-end developer, for Web Api debugging, besides using Postman, Apifox and other Web Api debugging tools, I think using Swagger for debugging should be more convenient and more commonly used.
So in the case of token authorization, every time you debug, you need to call the login API, then copy the returned token, paste it into the text box above, and click the Authorize button, isn't it very troublesome?
I'm so lazy, I really don't want to copy and paste the token anymore.
It would be nice if you could just call the login interface and the returned token would be automatically added and automatically authorized.
Let's go!
Step 1: Add the file
- In the webapi project, add the
wwwroot
Folder; - newly built
File to
wwwroot/swagger-ui/
directory, the directory didn't build itself, and of course the js file name itself is whatever you want it to be; - compiler
File contents:
("Custom JS has been loaded and executed.");
const originalFetch = ;
= function(...args) {
const [resource, config] = args;
return (this, args).then(response => {
// Check the requested URL
const requestUrl = new URL(, ).pathname;
if (("/login")) {
// Cloning the response for reading
().json().then(data => {
const token = ;
if (token) {
("Token received via fetch override:", token);
authorizeSwagger(token);
} else {
("Token not found in login response.");
}
}).catch(err => {
("Failed to parse login response:", err);
});
}
return response;
});
}
// Defining Authorization Functions
function authorizeSwagger(token) {
const bearerToken = 'Bearer ' + token;
("Setting Swagger UI Authorization with token:", bearerToken);
if ( && ) {
({
Bearer: {
name: 'Bearer',
schema: {
type: 'apiKey',
in: 'header',
name: 'Authorization',
description: '',
},
value: bearerToken,
}
});
("Authorization set successfully");
} else {
("Swagger UI authActions not available yet.");
}
}
Step 2: Enable Static File Service
exist in which the static file service is enabled;
var app = ();
// Enable the static file service
(); // Enable the static file service.
Step 3: Inject js script into SwaggerUI middleware
utilizationInjectJavascript
The way the aboveinjected into the SwaggerUI middleware.
// Enable Swagger
();
(options =>.
{
("/swagger-ui/");
("/swagger/v1/", "v1");
});
OK!
Let's give it a try!