受欢迎的博客标签

ASP.NET Core Web Api (1)-a new type called ActionResult<T>

Published

ASP.NET Core web API  offers the following options for web API controller action return types:

Specific type
IActionResult
ActionResult<T>

 

Specific type--Asynchronous action

 /// <summary>
        /// 读取STKInfo70.dat数据
        /// </summary>
        /// <returns></returns>

        public Task<List<STKInfo>>  GetStockInfo(int pageNo = 0)
        {
            _logger.LogInformation($"Executed GetSTKInfoData action starting...");

           // int pageNo=1;
          //  int.TryParse(pageNumber, out pageNo);
            // 读取STKInfo70.dat数据
            STKInfoDataProvider STKInfoDataProvider = new STKInfoDataProvider();

            List<STKInfo> listSTKInfo = STKInfoDataProvider.GetSTKInfo();

            STKInfoDataProvider.Close();
            List<STKInfo> result = listSTKInfo.Skip(pageNo * 10).Take(10).ToList();

            _logger.LogInformation($"Executed GetSTKInfoData action,total:{listSTKInfo.Count.ToString()}items");

            _logger.LogInformation($"Executed GetSTKInfoData action,total:{result.Count.ToString()}items");

            return Task.FromResult(result);
            
        }

 

  protected override async Task OnParametersSetAsync()
    {
        //come from:https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-5.0

        try
        {
            loadFailed = false;
            forecasts = await StockDataService.GetStockInfo(currentCount);

            Logger.LogInformation("Failed to load product ");
        }
        catch (Exception ex)
        {
            loadFailed = true;
            // Logger.LogWarning(ex, "Failed to load product {ProductId}", ProductId);
        }
    }

 

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> type in ASP.NET Core 

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.

ActionResult<T> type-Synchronous action

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

 

ActionResult<T> type -Asynchronous action

public async Task<ActionResult<Product>> CreateAsync(Product product)
{
    if (product.Description.Contains("XYZ Widget"))
    {
        return BadRequest();
    }

    await _repository.AddProductAsync(product);

    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}