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?
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).
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With