TOC

This article is currently in the process of being translated into Russian (~20% done).

Controllers:

Action Results

В предыдущей статье, мы обсудили Действия, которые определены как методы Контроллера. Действия вызываются, когда URL-запрос совпадает с Действием Контроллера (это производиться при помощи системы Маршрутизации). Когда Действие (метод) завершает свою работу, оно обычно возвращает что-либо клиенту. То, что возвращается, обычно имплементирует интерфейс IActionResult (или Задание (Task) Task<IActionResult>, если метод является асинхронным).

Как только Ваш Контроллер унаследует у встроенного базового класса-Контроллера (Microsoft.AspNetCore.Mvc.Controller), мы получаем широкий ряд методов-помощников для генерирования ответа (результата действия). Например, такой метод уже был использован в обучающем курсе: метод View(). Он берет файл совпадающего Вида и возвращает объект класса ViewResult, который имплементирует интерфейс IActionResult. После этого, ASP.NET MVC автоматически трансформирует его в ответ для браузера - в данном случае, в форме статус-кода "OK" и тела HTML.

A view is far from the only possible result of a Controller action, though. Since the result will eventually be returned to a browser, the available methods should cover all possible outcomes of a HTTP request, so a Controller action can of course also result in a redirect, a 404 (Page not Found) or any of the other HTTP status codes. Here's an incomplete list of the most interesting and useful methods for generating an Action result:

  • Content() - returns the specified string as plain text to the client (usually a browser)
  • View() - returns a View to the client
  • PartialView() - returns a Partial View (more on those elsewhere in this tutorial) to the client
  • File() - returns the content of a specified file to the client
  • Json() - returns a JSON response to the client
  • Redirect() and RedirectPermanent() - returns a redirect response to the browser (temporary or permanent), redirecting the user to another URL
  • StatusCode() - returns a custom status code to the client

There are many more, and you are of course free to implement your own or generate the result your self - most of these methods simply generates the relevant class with properties set accordingly. For instance, the Content() method simply generates an instance of the ContentResult class and fills the Content property with the value you pass into the method.

Since there are many types of responses which implements the IActionResult interface, your actions can return any of them, based on the logic of your method. A common use case for this is to return either a View or a piece of content if the requested content is found, or a 404 (Page not Found) error if its not found. It could look like this:

public IActionResult Details(int id)  
{  
	Product product = GetProduct(id);
	if (product != null)  
		return View(product);  
	return NotFound();  
}

In the first line, we try to load the requested product, using a to-be-implemented GetProduct() method. If the product is found, we return it inside of a View using the View() method - if not, we return a 404 error using the NotFound() helper method, which basically just creates an instance of the NotFoundResult class. So in this case, there are two possible outcomes of the action, but there could be even more, if needed - you are free to return anything that implements the IActionResult interface.

Заключение

An Action is a method on a Controller, usually accessible by a URL thanks to the Routing system. An Action will usually return an Action Result, based on the IActionResult interface. There are many helper methods available to aid you in generating the desired result(s) for your Action. These are the most important aspects to understand about an ASP.NET MVC Controller. In the coming articles we'll dig a bit deeper into some of the more advanced Controller topics.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!