ActionResult<T> in ASP.NET Core 2.1

One of the new features of ASP.NET Core 2.1 is, a new type called ActionResult<T> that allows you to return either the response type or any action result, while still indicating the response type. In this short post, we’ll see how this new type ActionResult<T> in ASP.NET Core 2.1 can be used and what issue it addresses.

ActionResult<T> in ASP.NET Core 2.1

Below is a very familiar piece of API action code.

public Product Get(int id)
{
    Product prod = null;
    // TODO: Get product by Id
    return prod;
}

Here, we are searching for a product by Id and returning the searched product. The return type of API action method is Product which helps in API documentation and also clients to know what response is expected. But, there is a problem with this code as this code will fail, when there is no product is found against the Id. The fix is also simple.

public ActionResult Get(int id)
{
    Product prod = GetProduct(id);
    if(prod == null)
    {
        return NotFound();
    }
    return ok(prod);
}

This works fine, but the API action method signature now no longer indicates the type of the returned object. The new type ActionResult <T> in ASP.NET Core 2.1 address this issue.

In ASP.NET Core 2.1, we can write the above code using the ActionResult <T> in the following way.

public ActionResult<Product> Get(int id)
{
    Product prod = GetProduct(id);
    if(prod == null)
    {
        return NotFound();
    }
    return prod;
}

Here, ActionResult will either return a Product object or ActionResult based on the result at runtime.

That’s it. You can read all my ASP.NET Core 2.1 post here.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

3 thoughts on “ActionResult<T> in ASP.NET Core 2.1

  1. Good addition. Previously, I used to do something like:

    [ProducesResponseType(typeof(Product), 200)]
    public ActionResult Get(int id)
    {
    Product prod = GetProduct(id);
    if(prod == null)
    {
    return NotFound();
    }
    return prod;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *