I have a .net core 3.1 webapi project. In some controllers, I need to execute some code that doesn't impact the response to the client.
In particular, I have a method that returns a json with a profile's information, which is called when user visits that profile's page. After get profile's information, I need to log that a user visits this page, but, for a faster response, I want to return response before this log operation.
[Route("[controller]")]
[ApiController]
public class ProfilesController : ControllerBase
{
[HttpGet("{id}")]
public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
{
Profile profile = await _profileService.GetByIDAsync(id);
// DO THIS OPERATION IN BACKGROUND AND DON'T WAIT TO RETURN RESPONSE
await _logService.LogProfileVisit(id);
return Ok(profile);
}
}
How can I do it?
Thanks.
Remove await keyword before _logService.LogProfileVisit(id);
This will prevent you from waiting for response
[Route("[controller]")]
[ApiController]
public class ProfilesController : ControllerBase
{
[HttpGet("{id}")]
public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
{
_logService.LogProfileVisit(id);
Profile profile = await _profileService.GetByIDAsync(id);
return Ok(profile);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With