官术网_书友最值得收藏!

IActionResult and ActionResult<T>

The IActionResult interface defines the contract <indexentry content="HTTP response:ActionResult"> for action method responses. The default implementation of the interface is provided by the ActionResult and ActionResult<T> types, but ASP.NET Core provides many derived response types that you can use to fully control the HTTP response that will be generated. Here is a short list of some of them:

  • EmptyResult: Generates an HTTP response with a success status code (200 OK) and an empty body.
  • ObjectResult: Generates a response with a body, where the body is a serialization of an object you provide. The object is serialized to the content type that was requested by the client. 
  • BadRequestResult: Generates a response with a BadRequst status code (400) that signals to the client that the given request is invalid.
  • ViewResult: Allows you to render a view, from a cshtml file, for example, and return the result (as HTML) to the client.
  • FileResult: Generates a response that contains file data. There are derived classes for various file reading formats.
  • RedirectResult: Generates a response with a temporary redirect (302) or permanent redirect status code (301) that contains the URL to navigate to.

Starting from ASP.NET Core 2.1, the ActionResult<T> type can be used as the return type of a controller action to make it explicit what the type of the body will be in a successful response, while still allowing for the return of other response types if needed. 

When an action with an explicit predefined return type returns its result, ASP.NET Core wraps the returned value in an ObjectResult instance.

For example, if GiveNTake receives a request to add a product with invalid request data, we send the client a BadRequestResult, and if the request was valid, we echo the request data with an ObjectResult, like this: 

[HttpPost("")]
public ActionResult<NewProductDTO> AddNewProduct([FromBody] NewProductDTO newProduct)
{
if (!ModelState.IsValid)
{
return new BadRequestResult();//(ModelState);
}
return newProduct;
}
主站蜘蛛池模板: 白山市| 临夏市| 湘潭市| 望奎县| 长兴县| 广灵县| 乌拉特后旗| 柘荣县| 双鸭山市| 都兰县| 龙游县| 芒康县| 崇州市| 乌拉特中旗| 满城县| 长寿区| 柳林县| 林州市| 东乡族自治县| 花垣县| 潞西市| 新泰市| 秦安县| 辽宁省| 荥阳市| 红安县| 定边县| 广宗县| 营口市| 甘孜县| 四会市| 岗巴县| 泽州县| 大同市| 康保县| 溧阳市| 庆安县| 四子王旗| 达拉特旗| 玉田县| 徐闻县|