WebApi interface returns four types of values

There are four main types of Webapi interface return values.

Void no return value

IHttpAcTIonResult

HttpResponseMessage

Custom type

Void no return value

Everyone knows that void declares a method with no return value, declaring an api controller method, for example:

c# WebApi interface return type detailed

Use postman, test interface:

c# WebApi之接口返回类型详解


It can be seen that the interface declared by void will not get the return value when the request succeeds, and will return the status code of http to 204, indicating that there is no return value.

IHttpAcTIonResult

IHttpAcTIonResult is the most commonly used return type of WebApi. Commonly used methods are: Json(T content), Ok(), Ok(T content), NotFound(), Content(HttpStatusCode statusCode, T value), BadRequest(), Redirect (string locaTIon), etc.

Json(T content)

In the abstract class of WebApi's ApiController, we encapsulate the Json(T content) method, which is similar to JsonResult in MVC.

c# WebApi interface return type detailed

c# WebApi之接口返回类型详解

Why can I return Json(T content), go to the definition of Json(T content) and find that it returns a JsonResult object?

c# WebApi之接口返回类型详解

Go to the definition of JsonResult and find that it implements the IHttpActionResult interface.

c# WebApi之接口返回类型详解

Of course, you can also use dynamic to return an object.

c# WebApi interface return type detailed

c# WebApi之接口返回类型详解

Pick To Light

Twinkle System Technology Co Ltd , https://www.pickingbylight.com

Posted on