IActionResult
在 ASP.NET Core 中,
IActionResult 是一个接口,用于表示控制器操作的结果。控制器中的每个操作方法(例如 HttpGet、HttpPost 等)都可以返回一个实现了 IActionResult 接口的对象。IActionResult 提供了一种灵活的方式来定义 HTTP 响应的内容、状态码和行为。作用
IActionResult 是 ASP.NET Core MVC 和 Web API 中用于处理 HTTP 响应的核心接口。它允许开发者根据不同的业务逻辑返回不同类型的响应,例如:-
成功响应(如
Ok()、CreatedAtAction()等) -
错误响应(如
BadRequest()、NotFound()等) -
重定向响应(如
RedirectToAction()、Redirect()等) -
自定义响应(如
Content()、File()等)
常见的 IActionResult 实现
ASP.NET Core 提供了许多内置的
IActionResult 实现,用于处理不同的场景。以下是一些常见的实现:1. 成功响应
-
Ok():返回 HTTP 状态码 200(OK)。csharp复制return Ok(); -
CreatedAtAction():返回 HTTP 状态码 201(Created),并提供一个指向新创建资源的 URI。csharp复制return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); -
NoContent():返回 HTTP 状态码 204(No Content)。csharp复制return NoContent();
2. 错误响应
-
BadRequest():返回 HTTP 状态码 400(Bad Request)。csharp复制return BadRequest("Invalid input"); -
NotFound():返回 HTTP 状态码 404(Not Found)。csharp复制return NotFound(); -
Unauthorized():返回 HTTP 状态码 401(Unauthorized)。csharp复制return Unauthorized(); -
Forbidden():返回 HTTP 状态码 403(Forbidden)。csharp复制return Forbid();
3. 重定向响应
-
RedirectToAction():重定向到另一个控制器操作。csharp复制return RedirectToAction("Index"); -
Redirect():重定向到指定的 URL。csharp复制return Redirect("https://example.com");
4. 自定义响应
-
Content():返回自定义的响应内容。csharp复制return Content("Hello, World!", "text/plain"); -
File():返回文件内容。csharp复制return File(fileContents, "application/pdf");
使用场景
IActionResult 的灵活性使其可以用于各种场景。以下是一些常见的使用场景:1. API 控制器
在 API 控制器中,通常根据业务逻辑返回不同的 HTTP 状态码和响应内容。例如:
csharp复制
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly MyDbContext _context;
public ProductsController(MyDbContext context)
{
_context = context;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound(); // 返回 404
}
return Ok(product); // 返回 200 和产品数据
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // 返回 400
}
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); // 返回 201
}
}
2. MVC 控制器
在 MVC 控制器中,
IActionResult 用于处理视图渲染、重定向等操作。例如:csharp复制
public class ProductsController : Controller
{
private readonly MyDbContext _context;
public ProductsController(MyDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var products = await _context.Products.ToListAsync();
return View(products); // 返回视图
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound(); // 返回 404
}
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound(); // 返回 404
}
return View(product); // 返回视图
}
}
总结
IActionResult 是 ASP.NET Core 中用于处理 HTTP 响应的核心接口,提供了丰富的内置实现,用于处理各种场景。通过使用 IActionResult,开发者可以灵活地定义控制器操作的返回结果,从而实现清晰、可维护的代码结构。
浙公网安备 33010602011771号