Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core 3 web api controller - code execution after sending response

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.

like image 765
Marco Avatar asked Jun 18 '26 20:06

Marco


1 Answers

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);
    }
}
like image 186
Farhad Zamani Avatar answered Jun 20 '26 10:06

Farhad Zamani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!