Ways to return the data from controller in Asp.net core


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

ASP.NET Core is a cross-platform, open-source, bias, rapid, and modular framework for developing high performance web applications. There are a few different ways in which you can occupy parameters for action methods in ASP .NET Core MVC. You can pass them by URL, query string, request header or body, or even a form.

All public methods of the control class are known as action methods. Because theyre created for a specific action or operation in the application. Therefore, the controller class can have several related action methods. As an example, adding a student is an action. Modifying student data is another action. Deleting a student is another action. So, the point you need to remember is that all related actions should be created inside a particular controller.

The action method can return many types. Lets modify the HomeController as shown below where we have a method that gives all the details to the students. Intentionally we returned the string from this method but as we progress in this course, we will discuss the actual implementation of this method. But for now, we are going to return the string just for learning.

using Microsoft.AspNetCore.Mvc;
namespace MVCWebApplication.Controllers
{
    public class StudentController : Controller
    {
        public string GetAllStudents()
        {
            return "Return All Students";
        }
    }
}

Starting from .NET Core version 2.1, there are still 3 types of WebApi responses that controller actions can return. All three types had their own pros and cons but all have lacked options to satisfy both REST and high level of testing.

There are three ways to return the data from action method in Asp.Net Core Web API.

  1. Specific type
  2. IActionResult
  3. ActionResult

Lets learn it all one by one.



Return a specific type from the Asp.Net Core Web API action method

The specific type is used to restore primitive (Boolean, Integer, String etc.) or tangled data from the action method.

Return string type from action method in Asp.net Core Web API,

[Route("website/name")]    
public string GetWebsiteName()    
{    
    return "Website XYZ";    
}  

Return a composite data from the action method in Asp.net Core Web API,

[Route("emplpyees/{id}")]  
public Employee GetEmployeeById(int id)  
{  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return employee;  
}  

The special type allows us to return,

  1. Any primitive data types from action method
  2. Any complex data object
  3. Collection of objects (like List etc)
  4. IEnumerable
  5. IAsyncEnumerable

Benefits of using a Specific type

There is no need to define the ProducesResponseType when using Swagger or a similar application as we have defined the return type.

Drawback of using a specific type

You cant return multiple types of data, lets say NotFound, ok, redirect, etc.

Return the IActionResult type from the Asp.Net Core Web API action method

ActionResult types represent different HTTP status codes and the IActionResult return type is suitable when numerous ActionResult return types are feasible in action. Any non-abstract class deriving from ActionResult is appropriate as a valid return type. A few common return types in this classification are BedRequestResult (400), OkObjectResult (200), and NotFoundResult (404). Alternatively, feature methods in the ControllerBase class can be used to return ActionResult types from the action.

The IActionResult is an interface and it is very powerful because it allows us to return multiple types. We can return data using some built-in methods like,

  1. OK ()
  2. Not Found ()
  3. Content ()
  4. File ()

Lets return the employee data using the IActionResult type

[Route("emplpyees/{id}")]  
public IActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return Ok(getEmployee );  
}  

In the code above, you can notice that we are returning two different types.

Benefits of using the IActionResult type

It allows us to return multiple types of data with status code and it is very important for RESTful API.

Drawback of using the IActionResult type

We need to use the ProducesResponseType explicitly because Swagger is not able to identify the output due to its ability to return multiple types of data.

[Route("emplpyees/{id}")]  
[ProducesResponseType(StatusCodes.Status201Created, Type = typeof(Employee))]  
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(Employee))]  
public IActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return Ok(getEmployee );  
}

Return the ActionResult type from Asp.Net Core web API action method


Op zoek naar een vertrouwd ASP.Net-softwareontwikkelingsbedrijf ?

Uw zoekopdracht eindigt hier.


ActionResult was introduced in Asp.net Core 2.1 and it can resume both specific types as well as the built-in (Asp.net Core) methods.

Lets go back to the primitive data type and not found data using the ActionResult type,

[Route("website/{websiteId}/name")]  
public ActionResult GetWebsiteName(int websiteId)  
{  
    if (websiteId == 0)  
    {  
        return NotFound();  
    }  
    return "Website XYZ";  
}  

We can also return any complex data return using the ActionResult type

[Route("emplpyees/{id}")]  
public ActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return getEmployee ;  
}  

Benefits of using the ActionResult type

It allows to return multiple types of data with the status codes.

We are explicitly specifying the return type, so there is no need to use the Type in ProducesResponseType attribute.

[Route("emplpyees/{id}")]  
[ProducesResponseType(StatusCodes.Status201Created)]  
[ProducesResponseType(StatusCodes.Status400BadRequest)]  
public ActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return getEmployee ;  
}  

Drawback of using the ActionResult type

Still the ProducesResponseType must be used for the status code.

Conclusion

In this article, we have learned the different ways to return the data from controller action method. Action Result classes in ASP.NET Core MVC provides a significant portion of the functionality that you will be able to use in your controllers. They return status codes, objects, files, other content and even redirect clients. As you become more familiar with ASP.NET Core MVC and its functionality. Although you might find it more comfortable to return specific type in the controller action, you may have your unit tests which do not cover your code properly and so can take the opening potential bus in the future.

Ways to return the data from controller in Asp.net core

ASP.NET Core is a cross-platform, open-source, bias, rapid, and modular framework for developing high performance web applications. There are a few different ways in which you can occupy parameters for action methods in ASP .NET Core MVC. You can pass them by URL, query string, request header or body, or even a form.

All public methods of the control class are known as action methods. Because theyre created for a specific action or operation in the application. Therefore, the controller class can have several related action methods. As an example, adding a student is an action. Modifying student data is another action. Deleting a student is another action. So, the point you need to remember is that all related actions should be created inside a particular controller.

The action method can return many types. Lets modify the HomeController as shown below where we have a method that gives all the details to the students. Intentionally we returned the string from this method but as we progress in this course, we will discuss the actual implementation of this method. But for now, we are going to return the string just for learning.

using Microsoft.AspNetCore.Mvc;
namespace MVCWebApplication.Controllers
{
    public class StudentController : Controller
    {
        public string GetAllStudents()
        {
            return "Return All Students";
        }
    }
}

Starting from .NET Core version 2.1, there are still 3 types of WebApi responses that controller actions can return. All three types had their own pros and cons but all have lacked options to satisfy both REST and high level of testing.

There are three ways to return the data from action method in Asp.Net Core Web API.

  1. Specific type
  2. IActionResult
  3. ActionResult

Lets learn it all one by one.



Return a specific type from the Asp.Net Core Web API action method

The specific type is used to restore primitive (Boolean, Integer, String etc.) or tangled data from the action method.

Return string type from action method in Asp.net Core Web API,

[Route("website/name")]    
public string GetWebsiteName()    
{    
    return "Website XYZ";    
}  

Return a composite data from the action method in Asp.net Core Web API,

[Route("emplpyees/{id}")]  
public Employee GetEmployeeById(int id)  
{  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return employee;  
}  

The special type allows us to return,

  1. Any primitive data types from action method
  2. Any complex data object
  3. Collection of objects (like List etc)
  4. IEnumerable
  5. IAsyncEnumerable

Benefits of using a Specific type

There is no need to define the ProducesResponseType when using Swagger or a similar application as we have defined the return type.

Drawback of using a specific type

You cant return multiple types of data, lets say NotFound, ok, redirect, etc.

Return the IActionResult type from the Asp.Net Core Web API action method

ActionResult types represent different HTTP status codes and the IActionResult return type is suitable when numerous ActionResult return types are feasible in action. Any non-abstract class deriving from ActionResult is appropriate as a valid return type. A few common return types in this classification are BedRequestResult (400), OkObjectResult (200), and NotFoundResult (404). Alternatively, feature methods in the ControllerBase class can be used to return ActionResult types from the action.

The IActionResult is an interface and it is very powerful because it allows us to return multiple types. We can return data using some built-in methods like,

  1. OK ()
  2. Not Found ()
  3. Content ()
  4. File ()

Lets return the employee data using the IActionResult type

[Route("emplpyees/{id}")]  
public IActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return Ok(getEmployee );  
}  

In the code above, you can notice that we are returning two different types.

Benefits of using the IActionResult type

It allows us to return multiple types of data with status code and it is very important for RESTful API.

Drawback of using the IActionResult type

We need to use the ProducesResponseType explicitly because Swagger is not able to identify the output due to its ability to return multiple types of data.

[Route("emplpyees/{id}")]  
[ProducesResponseType(StatusCodes.Status201Created, Type = typeof(Employee))]  
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(Employee))]  
public IActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return Ok(getEmployee );  
}

Return the ActionResult type from Asp.Net Core web API action method


Op zoek naar een vertrouwd ASP.Net-softwareontwikkelingsbedrijf ?

Uw zoekopdracht eindigt hier.


ActionResult was introduced in Asp.net Core 2.1 and it can resume both specific types as well as the built-in (Asp.net Core) methods.

Lets go back to the primitive data type and not found data using the ActionResult type,

[Route("website/{websiteId}/name")]  
public ActionResult GetWebsiteName(int websiteId)  
{  
    if (websiteId == 0)  
    {  
        return NotFound();  
    }  
    return "Website XYZ";  
}  

We can also return any complex data return using the ActionResult type

[Route("emplpyees/{id}")]  
public ActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return getEmployee ;  
}  

Benefits of using the ActionResult type

It allows to return multiple types of data with the status codes.

We are explicitly specifying the return type, so there is no need to use the Type in ProducesResponseType attribute.

[Route("emplpyees/{id}")]  
[ProducesResponseType(StatusCodes.Status201Created)]  
[ProducesResponseType(StatusCodes.Status400BadRequest)]  
public ActionResult GetEmployeeById(int id)  
{  
    if (id == 0)  
    {  
        return NotFound();  
    }  
    var getEmployee = new Employee() { Id = 1, Name = "ABC" }; 
    return getEmployee ;  
}  

Drawback of using the ActionResult type

Still the ProducesResponseType must be used for the status code.

Conclusion

In this article, we have learned the different ways to return the data from controller action method. Action Result classes in ASP.NET Core MVC provides a significant portion of the functionality that you will be able to use in your controllers. They return status codes, objects, files, other content and even redirect clients. As you become more familiar with ASP.NET Core MVC and its functionality. Although you might find it more comfortable to return specific type in the controller action, you may have your unit tests which do not cover your code properly and so can take the opening potential bus in the future.

  • Pin It
TOP