ActionResult是ASP.NET Core中表示控制器执行结果的抽象基类,通过其派生类或IActionResult接口实现多样化HTTP响应,如视图渲染、JSON数据返回、文件下载等,框架负责将其转换为实际响应;优先推荐使用IActionResult作为返回类型以提升灵活性和可维护性,因其支持多态返回不同结果类型;常见内置类型包括ViewResult、JsonResult、ContentResult、FileResult、RedirectToActionResult及各类StatusCodeResult,覆盖MVC与Web API主要场景;当内置类型不足时,可通过实现IActionResult接口自定义结果类,如CsvResult,以封装特定格式响应逻辑,增强代码复用性与控制力。
C#中的
ActionResult
ActionResult
ActionResult
ActionResult
在我看来,
ActionResult
HttpResponse
ActionResult
ViewResult
JsonResult
ActionResult
IActionResult
这确实是很多初学者,甚至一些有经验的开发者都会纠结的问题。在我看来,理解
ActionResult
IActionResult
IActionResult
ActionResult
IActionResult
ActionResult
ViewResult
JsonResult
IActionResult
那么,什么时候用
IActionResult
ActionResult
我个人倾向于在大多数情况下使用
IActionResult
IActionResult
IActionResult
public IActionResult GetProduct(int id) { var product = _productService.GetProductById(id); if (product == null) { return NotFound(); // 返回一个NotFoundResult,它实现了IActionResult } return Ok(product); // 返回一个OkObjectResult,它也实现了IActionResult }
这里,
NotFound()
Ok()
IActionResult
public NotFoundResult GetProduct(int id)
OkObjectResult
而
ActionResult
new ActionResult()
ViewResult
JsonResult
public ViewResult Index()
ViewResult
所以,我的建议是:
IActionResult
IActionResult
ActionResult
JsonResult
OkObjectResult
总之,
IActionResult
ActionResult
ActionResult
ASP.NET Core为我们内置了非常丰富的
ActionResult
以下是一些我经常使用的常见类型及其典型应用场景:
ViewResult
return View(model);
JsonResult
return Json(new { id = 1, name = "ProductA" });
ContentResult
return Content("Hello, World!", "text/plain");
FileResult
FileContentResult
FilePathResult
FileStreamResult
return File(bytes, "application/pdf", "report.pdf");
FileContentResult
RedirectResult
RedirectToActionResult
RedirectToRouteResult
RedirectResult
RedirectToActionResult
RedirectToRouteResult
return Redirect("https://example.com/new-page");
return RedirectToAction("Details", "Product", new { id = 1 });
StatusCodeResult
OkResult
NotFoundResult
BadRequestResult
UnauthorizedResult
NoContentResult
return Ok();
return NotFound();
return BadRequest("Invalid input.");
这些只是最常用的一部分,ASP.NET Core还提供了像
PartialViewResult
EmptyResult
PhysicalFileResult
ActionResult
有时候,内置的
ActionResult
ActionResult
自定义
ActionResult
IActionResult
ActionResult
ActionResult
ActionResult
IActionResult
核心在于实现
ExecuteResultAsync(ActionContext context)
context.HttpContext.Response
让我们以一个返回CSV数据的自定义
ActionResult
假设我们有一个
Product
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; // 假设Product模型 public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class CsvResult<T> : IActionResult { private readonly IEnumerable<T> _data; private readonly string _fileName; public CsvResult(IEnumerable<T> data, string fileName = "data.csv") { _data = data; _fileName = fileName; } public async Task ExecuteResultAsync(ActionContext context) { var response = context.HttpContext.Response; response.ContentType = "text/csv"; response.Headers.Add("Content-Disposition", $"attachment; filename=\"{_fileName}\""); using (var writer = new StreamWriter(response.Body, Encoding.UTF8)) { // 写入CSV头部 var properties = typeof(T).GetProperties(); await writer.WriteLineAsync(string.Join(",", properties.Select(p => p.Name))); // 写入数据行 foreach (var item in _data) { var values = properties.Select(p => p.GetValue(item)?.ToString() ?? ""); await writer.WriteLineAsync(string.Join(",", values)); } await writer.FlushAsync(); } } }
然后在你的控制器中,你可以这样使用它:
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; [ApiController] [Route("[controller]")] public class ProductsController : ControllerBase { private readonly List<Product> _products = new List<Product> { new Product { Id = 1, Name = "Laptop", Price = 1200.50m }, new Product { Id = 2, Name = "Mouse", Price = 25.99m }, new Product { Id = 3, Name = "Keyboard", Price = 75.00m } }; [HttpGet("csv")] public IActionResult GetProductsAsCsv() { return new CsvResult<Product>(_products, "products.csv"); } }
通过这个例子,我们可以看到自定义
ActionResult
自定义
ActionResult
掌握自定义
ActionResult
以上就是C#的ActionResult是什么?有哪些类型?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号