When an HTTP request is made to your ASP.NET Core application, it is always possible that the request is aborted. For instance when the user closes it browsers without waiting for the response. In this case, you may want to stop all the work to avoid consuming resources.
Here are 2 possible approaches on how to handle this scenario. A first option is to check the HttpContext.RequestAborted
property:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ApiController] | |
[Route("[controller]")] | |
public class ProductsController : ControllerBase | |
{ | |
private IRepository _repository; | |
public ProductsController(IRepository repository) | |
{ | |
_repository=repository; | |
} | |
[HttpGet] | |
public async Task<List<Product>> Get() | |
{ | |
CancellationToken cancellationToken = HttpContext.RequestAborted; | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
// The client has aborted the request | |
} | |
return await _repository.GetProducts(cancellationToken); | |
} | |
} |
A second option is to let the Modelbinder do itās work and add a parameter of type CancellationToken
to the action:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ApiController] | |
[Route("[controller]")] | |
public class ProductsController : ControllerBase | |
{ | |
private IRepository _repository; | |
public ProductsController(IRepository repository) | |
{ | |
_repository=repository; | |
} | |
[HttpGet] | |
public async Task<List<Product>> Get(CancellationToken cancellationToken) | |
{ | |
return await _repository.GetProducts(cancellationToken); | |
} | |
} |