ZetCode

ASP.NET IHttpActionResult

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 IHttpActionResult 接口。该接口提供了一种强大的方式,可以从 Web API 操作返回 HTTP 响应。

ASP.NET Web API 是一个用于构建 HTTP 服务的框架,这些服务可以触及广泛的客户端。IHttpActionResult 有助于创建标准化的 HTTP 响应。

基本定义

IHttpActionResult 是 ASP.NET Web API 中的一个接口,代表 HTTP 响应。它封装了创建 HttpResponseMessage 的逻辑。

该接口包含一个名为 ExecuteAsync 的方法。此方法异步创建一个 HttpResponseMessage 实例。它允许延迟执行。

与返回原始数据相比,使用 IHttpActionResult 具有多项优势。它提高了可测试性,并将响应创建与操作逻辑分离开来。

ASP.NET 通过 ApiController 类提供了多个内置实现。这些包括 Ok、NotFound、BadRequest 以及其他辅助方法。

当您需要返回不同的 HTTP 状态码或需要以复杂的方式自定义响应时,IHttpActionResult 特别有用。

ASP.NET IHttpActionResult 示例

以下示例演示了一个使用 IHttpActionResult 的 Web API 控制器。

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();

这设置了一个基本的 ASP.NET 应用程序,并支持控制器。MapControllers 方法为控制器启用属性路由。

Controllers/CustomersController.cs
using Microsoft.AspNetCore.Mvc;
using System.Net;

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    private static List<Customer> _customers = new()
    {
        new Customer(1, "John Doe", "john@example.com"),
        new Customer(2, "Jane Smith", "jane@example.com"),
        new Customer(3, "Bob Johnson", "bob@example.com")
    };

    [HttpGet]
    public IHttpActionResult GetAllCustomers()
    {
        return Ok(_customers);
    }

    [HttpGet("{id}")]
    public IHttpActionResult GetCustomerById(int id)
    {
        var customer = _customers.FirstOrDefault(c => c.Id == id);
        if (customer == null)
        {
            return NotFound();
        }
        return Ok(customer);
    }

    [HttpPost]
    public IHttpActionResult CreateCustomer([FromBody] Customer customer)
    {
        if (customer == null)
        {
            return BadRequest("Customer data is required");
        }

        if (_customers.Any(c => c.Email == customer.Email))
        {
            return Conflict("Customer with this email already exists");
        }

        customer.Id = _customers.Max(c => c.Id) + 1;
        _customers.Add(customer);

        return CreatedAtAction(
            nameof(GetCustomerById),
            new { id = customer.Id },
            customer);
    }

    [HttpPut("{id}")]
    public IHttpActionResult UpdateCustomer(int id, [FromBody] Customer customer)
    {
        if (customer == null || customer.Id != id)
        {
            return BadRequest();
        }

        var existingCustomer = _customers.FirstOrDefault(c => c.Id == id);
        if (existingCustomer == null)
        {
            return NotFound();
        }

        existingCustomer.Name = customer.Name;
        existingCustomer.Email = customer.Email;

        return StatusCode(HttpStatusCode.NoContent);
    }
}

public record Customer(int Id, string Name, string Email);

此控制器演示了各种 IHttpActionResult 返回类型。Ok 方法返回 200 OK 响应,并将指定的数据包含在响应中。

当找不到客户时,NotFound 方法返回 404 Not Found。BadRequest 方法对于无效输入返回 400 Bad Request。

CreatedAtAction 方法返回 201 Created 响应,并包含一个指向新资源的 Location 标头。StatusCode 允许返回任何 HTTP 状态码。

该示例展示了 IHttpActionResult 如何提供一种清晰的方式来返回不同的 HTTP 响应。每种方法都清楚地指示了其响应类型。

来源

Microsoft ASP.NET Web API 返回类型文档

在本文中,我们探讨了 ASP.NET 8 中的 IHttpActionResult 接口。这个强大的功能简化了返回标准化的 HTTP 响应的过程。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出所有 ASP.NET 教程