要在ASP.NET Swagger中展示错误,您需要遵循以下步骤:
dotnet add package Swashbuckle.AspNetCore
Startup.cs
文件中,将Swashbuckle添加到ConfigureServices
方法中:public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
Configure
方法中,将Swagger添加到中间件管道中:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
[ApiExplorerSettings(IgnoreApi = true)]
属性。这将告诉Swagger忽略此操作。例如:[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet("ignore")]
public IActionResult IgnoreMethod()
{
return Ok("This method will not be shown in Swagger UI.");
}
[ApiResponse]
属性。例如:[ApiResponse(statusCode: 400, description: "Bad Request", content: new[] { new { property = "value" } })
[HttpGet("badrequest")]
public IActionResult BadRequestMethod()
{
return BadRequest("This is a bad request.");
}
请注意,这些步骤适用于Swashbuckle.AspNetCore 5.0及更高版本。如果您使用的是早期版本,可能需要稍微调整配置和代码。