【发布时间】:2022-11-14 20:51:51
【问题描述】:
我想用 ASP.net Core 创建一个 WebAPI。 API 受授权保护。但并非所有功能都受到保护! 我怎样才能用 Swagger 实现这一点?
这是我的 Swagger 设置:
[...]
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
[...]
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = "swagger/index.html";
});
}
[...]
函数如下所示:
/// <summary>
/// Registriert einen neuen User
/// </summary>
/// <returns></returns>
/// <response code="200">...</response>
/// <response code="400">...</response>
[HttpPost]
[Route("Register")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Register([FromBody] UserRegistrationDto user)
{ [...] }
在 Swagger 中,它看起来像这样:
锁表示此功能可能/需要授权。我想卸下锁。但仅限于此功能。我怎么能在 C# 中做到这一点?
(swagger 文件是自动生成的,我不想修改导出的 .yaml 或 .json 文件。所以我需要一个直接在 c# 代码或 swagger 配置中工作的解决方案。)
【问题讨论】:
-
如果注册不需要身份验证,为什么
[ProducesResponseType(StatusCodes.Status401Unauthorized)]?您可以尝试添加[AllowAnonymous]属性吗?
标签: c# asp.net-core-webapi swagger-ui openapi swashbuckle.aspnetcore