ASP。 NET Core Web API 项目没有将请求头“Authorization”生成到“swagger.json”文档文件中

问题描述 投票:0回答:1

ASP。 NET Core Web API 项目没有将请求头“Authorization”生成到“swagger.json”文档文件中

尝试将请求标头“Authorization”输出到“swagger.json”文件

项目信息:

  • 项目:ASP.NET Core Web API
  • 框架:.NET 8.0

  1. 无错误输出

  2. 我确信我已经在“MyProject.csproj”中启用了文档生成:

    正确

  3. 通过清理解决方案并重建并启动应用程序,您可以看到“MyProject.xml”文件已输出。

  4. 打开“MyProject.xml”文件可以看到请求头信息已经生成了:

    获取用户信息 代币 响应模型
  5. 访问“https://localhost:12345/swagger/v1/swagger.json”没有看到请求头“Authorization”生成到“swagger.json”文件中:

enter image description here

这是我的“Program.cs”代码:

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);
        }
    }
}
c# asp.net-core swagger .net-8.0
1个回答
0
投票

我在Swagger官方文档中找到了答案,结果发现这些参数名是不允许使用的: https://swagger.io/docs/specification/describing-parameters/

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.