ZetCode

ASP.NET ActionResult

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 ActionResult 类型。ActionResult是 ASP.NET 应用程序中控制器操作的基本返回类型。

ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。ActionResult 提供了一种灵活的方式来返回 HTTP 响应。

基本定义

ActionResult 是 ASP.NET 中的一个基类,代表操作方法的返回结果。它封装了响应数据和 HTTP 状态码。

ActionResult 提供了各种派生类型,用于常见的 HTTP 响应,如 OkResult、NotFoundResult 和 BadRequestResult。这些简化了返回标准 HTTP 响应的过程。

使用 ActionResult 可以使您的 API 更具灵活性和可维护性。它允许在需要时从同一个操作方法返回不同的响应类型。

ASP.NET ActionResult 示例

以下示例演示了 Web API 中各种 ActionResult 的返回类型。

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

var app = builder.Build();

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

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

Controllers/BooksController.cs
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
    private static List<Book> _books = new()
    {
        new Book(1, "The Great Gatsby", "F. Scott Fitzgerald"),
        new Book(2, "1984", "George Orwell"),
        new Book(3, "To Kill a Mockingbird", "Harper Lee")
    };

    [HttpGet]
    public ActionResult<IEnumerable<Book>> GetAllBooks()
    {
        return Ok(_books);
    }

    [HttpGet("{id}")]
    public ActionResult<Book> GetBookById(int id)
    {
        var book = _books.FirstOrDefault(b => b.Id == id);
        if (book == null) return NotFound();
        return Ok(book);
    }

    [HttpPost]
    public ActionResult<Book> AddBook([FromBody] Book newBook)
    {
        if (newBook == null) return BadRequest();
        
        newBook.Id = _books.Max(b => b.Id) + 1;
        _books.Add(newBook);
        
        return CreatedAtAction(nameof(GetBookById), 
            new { id = newBook.Id }, newBook);
    }

    [HttpPut("{id}")]
    public ActionResult UpdateBook(int id, [FromBody] Book updatedBook)
    {
        var existingBook = _books.FirstOrDefault(b => b.Id == id);
        if (existingBook == null) return NotFound();
        
        existingBook.Title = updatedBook.Title;
        existingBook.Author = updatedBook.Author;
        
        return NoContent();
    }

    [HttpDelete("{id}")]
    public ActionResult DeleteBook(int id)
    {
        var book = _books.FirstOrDefault(b => b.Id == id);
        if (book == null) return NotFound();
        
        _books.Remove(book);
        return NoContent();
    }
}

public record Book(int Id, string Title, string Author);

此控制器演示了 RESTful API 的各种 ActionResult 返回类型。ActionResult<T> 泛型类型提供了更好的 Swagger 文档和类型安全性。

GetAllBooks 方法返回一个带有图书列表的 OkObjectResultGetBookById 返回图书或 404 状态码。

AddBook 方法展示了如何返回带有位置头的 201 Created 响应。UpdateBookDeleteBook 对成功操作返回 204 NoContent。

此示例涵盖了所有 CRUD 操作,并使用了适当的 HTTP 状态码和响应类型。它展示了 ActionResult 在处理不同响应场景方面的灵活性。

来源

Microsoft ASP.NET 操作返回类型文档

在本文中,我们探讨了 ASP.NET 8 中的 ActionResult 类型。这个强大的功能提供了一种灵活的方式来从操作返回 HTTP 响应。

作者

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

列出所有 ASP.NET 教程