MVC Core IActionResult meaning

瘦欲@ 提交于 2019-12-05 03:16:40

问题


What is an IActionResult? I tried looking at MSDN and other sites, but need general, common easy to understand answer.

MSDN IActionResult

Example:

public IActionResult About() {
    ViewData["Message"] = "About Page";
    return View();
}

回答1:


In general terms IActionResult type is a base abstraction of an action result. It is used as the base of other derived action results that represent specific response types, of which there are many.

Reference Asp.Net Core Action Results Explained

IActionResult and ActionResult

IActionResult and ActionResult work as a container for other action results, in that IActionResult is an interface and ActionResult is an abstract class that other action results inherit from. So they can’t be newed up and returned like other action results. IActionResult and ActionResult have not much of a different from usability perspective, but since IActionResult is the intended contract for action results, it’s better to use it as opposed to ActionResult. IActionResult/ActionResult should be used to give us more flexibility, like when we need to return different type of response based on user interaction.

To quote official documentation Found here Controller action return types in ASP.NET Core Web API

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Some common return types falling into this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200).




回答2:


IActionResult specifies how the server should respond to the request, such as writing data to the response or returning an error status code.

For example, Microsoft.AspNetCore.Mvc.JsonResult serializes the object passed from the constructor and writes the serialized JSON data to the response and sets the MIME type to application/JSON. It can be understood as "This request results as a JSON string".



来源:https://stackoverflow.com/questions/49503802/mvc-core-iactionresult-meaning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!