ASP.NET HttpGet
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 HttpGet 属性。此属性对于构建响应 GET 请求的 RESTful API 和 Web 服务至关重要。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。HttpGet 属性简化了路由和请求处理。
基本定义
ASP.NET 中的 HttpGet 属性标记一个控制器操作方法,使其仅响应 HTTP GET 请求。GET 是用于从服务器检索数据的最常用的 HTTP 方法。
当应用于操作方法时,HttpGet 指定在收到 GET 请求时应调用该方法。它可以与路由模板一起使用来定义自定义 URL 模式。
HttpGet 是 ASP.NET 属性路由系统的一部分,该系统比传统路由提供了对 URI 模式的更多控制。它通常在 Web API 控制器中使用。
ASP.NET HttpGet 示例
下面的示例演示了一个使用 HttpGet 的基本 Web API 控制器。
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();
这设置了一个基本的 ASP.NET 应用程序,并支持控制器。MapControllers 方法为控制器启用属性路由。
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List<Product> _products = new()
{
new Product(1, "Laptop", 999.99m),
new Product(2, "Mouse", 19.99m),
new Product(3, "Keyboard", 49.99m)
};
[HttpGet]
public IActionResult GetAllProducts()
{
return Ok(_products);
}
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
return Ok(product);
}
[HttpGet("search")]
public IActionResult SearchProducts([FromQuery] string name)
{
var results = _products.Where(p =>
p.Name.Contains(name, StringComparison.OrdinalIgnoreCase));
return Ok(results);
}
}
public record Product(int Id, string Name, decimal Price);
此控制器演示了三种不同的 HttpGet 场景。第一个方法在访问基本路由 /api/products 时返回所有产品。
第二个方法使用路由参数 {id} 来获取特定产品。第三个方法展示了使用 [FromQuery] 进行查询参数绑定。
ApiController 属性为无效模型和其他 Web API 约定启用了自动 HTTP 400 响应。Route 为此控制器中的所有操作设置了基本路径。
该示例展示了 HttpGet 如何用于不同的 GET 场景:集合检索、单个项目检索和筛选搜索。每个方法都返回适当的 HTTP 状态代码。
来源
在本文中,我们探讨了 ASP.NET 8 中的 HttpGet 属性。这项强大的功能简化了用于检索数据的 RESTful 端点的创建。