ASP.NET ResponseType
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 ResponseType 属性。此属性对于在 Swagger 和 OpenAPI 中记录 API 响应至关重要。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。ResponseType 属性有助于定义预期的响应格式。
基本定义
ASP.NET 中的 ResponseType 属性指定了操作方法返回的响应类型。这对于 API 文档工具尤其有用。
当应用于操作方法时,ResponseType 会将预期的响应模型告知 Swagger 和客户端。这提高了 API 的可发现性和文档性。
ResponseType 可用于成功和错误响应。它可以指定简单类型、复杂对象或集合。它通常在 Web API 中使用。
ASP.NET ResponseType 示例
以下示例演示了一个使用 ResponseType 的 Web API 控制器。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers();
app.Run();
这会设置一个支持 Swagger 的 ASP.NET 应用程序。Swagger 将使用 ResponseType 属性来生成准确的 API 文档。
using Microsoft.AspNetCore.Mvc;
using System.Net;
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class WeatherController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("forecast")]
[ProducesResponseType(typeof(IEnumerable<WeatherForecast>),
StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult GetForecast([FromQuery] int days = 5)
{
if (days <= 0 || days > 30)
{
return BadRequest("Days must be between 1 and 30.");
}
var forecast = Enumerable.Range(1, days).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
Summaries[Random.Shared.Next(Summaries.Length)]
))
.ToArray();
return Ok(forecast);
}
[HttpGet("current/{city}")]
[ProducesResponseType(typeof(WeatherForecast), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetCurrentWeather(string city)
{
if (string.IsNullOrWhiteSpace(city))
{
return BadRequest("City name is required.");
}
if (city.Equals("unknown", StringComparison.OrdinalIgnoreCase))
{
return NotFound();
}
var weather = new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now),
Random.Shared.Next(-20, 55),
Summaries[Random.Shared.Next(Summaries.Length)]
);
return Ok(weather);
}
}
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
此控制器演示了 ResponseType 的用法,其中包含两个操作方法。第一个方法返回多天的天气预报,并记录了各种响应类型。
ProducesResponseType 属性指定了可能的响应类型和状态码。Swagger 将使用此信息来生成准确的 API 文档。
第一个方法显示了成功 (200)、未找到 (404) 和服务器错误 (500) 的响应。第二个方法演示了单个对象返回以及对错误请求 (400) 的处理。
该示例展示了 ResponseType 如何改进 API 文档和客户端理解。它有助于 Swagger 等工具生成更好的文档和客户端代码。
来源
Microsoft ASP.NET Web API 返回类型文档
在本文中,我们探讨了 ASP.NET 8 中的 ResponseType 属性。这一强大的功能增强了 API 文档和客户端开发体验。