Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I return ActionResult instead of object?

Assuming that I have application .NET Core 2.1 Web API + Angular 7

Why should I always returns ActionResult? Is there any difference between this:

public ActionResult<MyDTO> GetData(){
    return new MyDTO();
}

and that:

public MyDTO GetData(){
    return new MyDTO();
}

In both cases I'll receive object on UI, and both returns code 200. So is just good practice to using ActionResult, or what?

like image 422
DiPix Avatar asked Nov 12 '18 12:11

DiPix


People also ask

What should I return in ActionResult?

The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type. Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200).

Can I return ActionResult Instead of view results?

First to Understand---ActionResult and ViewResult are basically a return type for an method(i.e Action in MVC). Second The Difference is --- ActionResult can return any type of Result Whereas ViewResult can return result type of View Only.

Which return type should be used when multiple ActionResult?

As you can see, the same action method “Index” is returning two different types named Content and View; if you want to return multiple types, you have to use base type as ActionResult.

What is the difference between ActionResult and IActionResult?

IActionResult is an interface and ActionResult is an implementation of that interface. ActionResults is an abstract class and action results like ViewResult, PartialViewResult, JsonResult, etc., derive from ActionResult.


1 Answers

When you use this:

public MyDTO GetData(){
    return new MyDTO();
}

You cannot return anything that's not an instance of MyDTO, besides throwing an exception.

When you use IActionResult<T> you are saying that you may return an instance of MyDTO, but you don't have to. You can return BadRequest, InternalServerError or whatever suits the API/business needs.

For example:

public IActionResult<MyDTO> GetData() 
{
    if (!User.Identity.IsAuthenticated)
    {
        return Forbidden();
    }

    var data = _someService.GetSomeData();

    if (data == null)
    {
        return NotFound();
    }

    return Ok(data);
}
like image 130
Camilo Terevinto Avatar answered Oct 03 '22 15:10

Camilo Terevinto