Thursday, May 17, 2018

ASP.NET Core 2.1: ActionResult<TValue>

ASP.NET Core 2.1 is almost released, we now have access to ASP.NET Core 2.1 RC1. Among other nice features like SignalR (Yes, SignalR is included in ASP.NET Core 2.1) which is getting shipped with ASP.NET Core 2.1, one of my favorites is the introduction of ActionResult<TValue>.

Consider the following API action with ASP.NET Core prior to 2.1.
public Employee Get(int id)
{
    Employee employee = null;
 
    // TODO: Get employee by Id
 
    return employee;
}
So this is very simple, and we are searching for an Employee by Id and returning an Employee. Having Employee is the return type here is very useful for things like documenting the API using Swagger for instance.

But this looks like a bad code, what if there is no Employee by given Id. In that we don’t usually return null, we return HTTP Status Code: NotFound.

But if we are to return that, we no longer can return an Employee type, we are returning an IActionResult. And the code changes to following.
public ActionResult Get(int id)
{
    Employee employee = null;
 
    // TODO: Get employee by Id
 
    if (employee == null)
    {
        return NotFound();
    }
 
    return Ok(employee);
}
Now there is no easy way to know what the encapsulated type of the result.

But we don’t have to face this situation any longer. ASP.NET Core 2.1 introduces this new return type ActionResult<TValue>.
public ActionResult<Employee> Get(int id)
{
    Employee employee = null;
 
    // TODO: Get employee by Id
 
    if (employee == null)
    {
        return NotFound();
    }
 
    return employee;
}
So here ActionResult<Employee> will either wrap Employee or ActionResult based on the result at runtime.

I like this very much, hope you all do!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment