Action Return Types in ASP.NET Core MVC
An action return type determines what response a controller sends to the client.
| Return type | Purpose | Example |
|---|---|---|
IActionResult |
Allows different result types | return View() or return NotFound() |
ActionResult<T> |
Returns typed data or an HTTP result | return product or return NotFound() |
| Specific result type | Returns one fixed result | ViewResult, JsonResult |
| Model type | Returns data directly, mainly in APIs | return product; |
void |
Returns no content | Generally not recommended |
Common MVC Action Results
| Result | Purpose | Example |
|---|---|---|
ViewResult |
Returns a Razor View | return View(model); |
PartialViewResult |
Returns a partial View | return PartialView("_Product", model); |
JsonResult |
Returns JSON data | return Json(product); |
ContentResult |
Returns plain text or HTML | return Content("Success"); |
RedirectResult |
Redirects to a URL | return Redirect("/Products"); |
RedirectToActionResult |
Redirects to another action | return RedirectToAction("Index"); |
RedirectToRouteResult |
Redirects using a named route | return RedirectToRoute("default"); |
FileResult |
Returns a downloadable or displayable file | return File(bytes, "application/pdf"); |
StatusCodeResult |
Returns an HTTP status code | return StatusCode(500); |
NotFoundResult |
Returns HTTP 404 | return NotFound(); |
BadRequestResult |
Returns HTTP 400 | return BadRequest(); |
UnauthorizedResult |
Returns HTTP 401 | return Unauthorized(); |
ForbidResult |
Returns HTTP 403 | return Forbid(); |
NoContentResult |
Returns HTTP 204 | return NoContent(); |
OkObjectResult |
Returns HTTP 200 with data | return Ok(product); |
MVC Example
public IActionResult Details(int id)
{
var product = _service.GetById(id);
if (product == null)
return NotFound();
return View(product);
}
The action can return either:
NotFoundResultViewResult
Therefore, the return type is IActionResult.
Key Points
IActionResultis commonly used when an action can return different responses.- MVC applications commonly return
ViewResult. ActionResult<T>is mainly used in Web API controllers.- Use
RedirectToAction()after successful form submissions. - Use
File()to return files. - Choose the most specific return type when the action always returns the same result.