ASP。 NET Core Web API 项目没有将请求头“Authorization”生成到“swagger.json”文档文件中
尝试将请求标头“Authorization”输出到“swagger.json”文件
项目信息:
无错误输出
我确信我已经在“MyProject.csproj”中启用了文档生成:
正确
通过清理解决方案并重建并启动应用程序,您可以看到“MyProject.xml”文件已输出。
打开“MyProject.xml”文件可以看到请求头信息已经生成了:
获取用户信息 代币 响应模型访问“https://localhost:12345/swagger/v1/swagger.json”没有看到请求头“Authorization”生成到“swagger.json”文件中:
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);
}
}
}
我在Swagger官方文档中找到了答案,结果发现这些参数名是不允许使用的: https://swagger.io/docs/specification/describing-parameters/