Harsha W
Harsha W

Reputation: 3366

Return HttpStatus code in a method returns Task<List<T>>

How can I return different types of HttpStatus codes in a method which returns a list? If the method hits try block it should return 200(Automatically it happens since it is a successful response). Need to return 404 if it hits the catch block.

[HttpGet]
[Route("{customerId}")]
public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId)
{
    try
    {
         List<CategoryEntity> categoryEntities = _categoryRepository.GetAllCategoriesByCustomerId(customerId);
         return categoryEntities;
    }
    catch (Exception ex)
    {
         _logger.LogError(ex, ex.Message);
         return null;
    }
}

Upvotes: 2

Views: 2444

Answers (3)

cdonner
cdonner

Reputation: 37668

This is an old question, but I keep running into this and even though James basically gave the answer, it takes me a moment too long to remember the obvious: just add ActionResult into your Return type cascade, like so:

public async Task<ActionResult<List<CategoryEntity>>> GetCategoryByCustomerId(...

Upvotes: 1

James
James

Reputation: 36

If you want your method to produce specific HTTP status codes, your method should return an IActionResult. The ActionResult types are representative of HTTP status codes (ref).

For your method, you would return an OkResult inside of your try block to have the method respond with an HTTP 200 and a NotFoundResult inside of your catch for it to respond with an HTTP 404.

You can pass the data that you want to send back to the client (i.e. your List<T>) to OkResults's constructor.

Upvotes: 2

Nirav Patel
Nirav Patel

Reputation: 16

[HttpGet]
[Route("{customerId}")]
public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId)
{
    try
    {
        List<CategoryEntity> categoryEntities = _categoryRepository.GetAllCategoriesByCustomerId(customerId);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return categoryEntities;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, ex.Message);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
        return null;
    }
}

Upvotes: 0

Related Questions