Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using IActionResult as result type in Actions

Tags:

What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?

Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!

like image 644
Zeus82 Avatar asked Jun 23 '16 17:06

Zeus82


People also ask

Why do we use IActionResult?

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

Why we use IActionResult in Web API?

The IActionResult is an interface and it is used to return multiple types of data. For example, if you want to return NotFound, OK, Redirect, etc. data from your action method then you need to use IActionResult as the return type from your action method.

What is the return type of IActionResult?

Returning IActionResult is helpful in scenarios where the web API action is supposed to return multiple types. e.g. if record not found, then action can return NotFoundResult and if Record is found then API can return 200 OK with record to the caller.

What is the difference between IActionResult and IHttpActionResult?

IHttpActionResult is for ASP.NET Web Api, while IActionResult is for ASP.NET Core. There's no such thing as "Web Api" in ASP.NET Core. It's all just "Core". However, some people still refer to creating an ASP.NET Core API as a "Web Api", which adds to the confusion.


2 Answers

The main advantage is that you can return error/status codes or redirects/resource urls.

For example:

public IActionResult Get(integer id)  {     var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();      if(user == null)      {         // Returns HttpCode 404         return NotFound();     }      // returns HttpCode 200     return ObjectOk(user); } 

or

public IActionResult Create(User user)  {     if(!ModelState.IsValid)      {         // returns HttpCode 400         return BadRequest(ModelState);     }      db.Users.Add(user);     db.SaveChanges();      // returns HttpCode 201     return CreatedAtActionResult("User", "Get", new { id = user.Id} ); } 
like image 116
Tseng Avatar answered Sep 18 '22 12:09

Tseng


The main advantage is that you can easily test your code using a mocking framework.

And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.

like image 24
gnllucena Avatar answered Sep 20 '22 12:09

gnllucena