The ASP. NET Core Web API project did not generate the request header "Authorization" into the "swagger. json" document file
tried to output the request header "Authorization" to the "swagger.json" file
Project Info:
No error output
I am certain that I have enabled document generation in "MyProject. csproj":
True
And by cleaning up the solution and rebuilding and launching the application, you can see that the "MyProject.xml" file has been output.
Open the "MyProject.xml" file and i can see that the request header information has been generated:
GetUserInfo Token ResponseModelVisit“ https://localhost:12345/swagger/v1/swagger.json ”I did not see the request header "Authorization" being generated into the "swagger. json" file:
builder.Services.AddSwaggerGen(swagger =>
{
swagger.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject", Version = "1.0.1" });
swagger.SwaggerDoc("v2", new OpenApiInfo { Title = "MyProject", Version = "2.0" });
// Include xml file
swagger.IncludeXmlComments(AppContext.BaseDirectory + Assembly.GetEntryAssembly().GetName().Name + ".xml", true);
swagger.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new()
{
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Description = "Bearer Token",
Name = "Authorization",
BearerFormat = "JWT",
Scheme = JwtBearerDefaults.AuthenticationScheme
});
swagger.AddSecurityRequirement(new()
{
{
new OpenApiSecurityScheme()
{
Reference = new OpenApiReference()
{
Type = ReferenceType.SecurityScheme,
Id = JwtBearerDefaults.AuthenticationScheme
}
},
new string[]{ }
}
});
});
// Other Code...
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(swagger =>
{
swagger.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
swagger.SwaggerEndpoint("/swagger/v2/swagger.json", "v2");
});
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<IdentityAuthenticationMiddleware>();
app.MapControllers();
app.Run();
/// <summary>
/// UserInfo
/// </summary>
[ApiController]
[Route("api/[controller]/[action]")]
[Authorize(Roles = "User,Admin")]
public class UserInfoController(HttpRequestModel httpRequestModel) : ControllerBase
{
private readonly HttpRequestModel _httpRequest = httpRequestModel;
/// <summary>
/// GetUserInfo
/// </summary>
/// <param name="authorization">Token</param>
/// <returns>ResponseModel</returns>
[HttpGet]
public ResponseModel GetUserInfo([Required][FromHeader(Name = "Authorization")] string authorization)
{
using (UserInfoBll userInfoBll = new())
{
return userInfoBll.GetUserInfoModel(_httpRequest.Token.UserId);
}
}
}
I found the answer in the official Swagger documentation, and it turns out that these parameter names are not allowed to be used: https://swagger.io/docs/specification/describing-parameters/