Home > Software engineering >  ASP.NET Core, On request immediately return 200, then run a method
ASP.NET Core, On request immediately return 200, then run a method

Time:10-03

can I call a GET request, and have it immediately return a 200 response, then run a method.

Thank you for any help.

CodePudding user response:

You can't - no code is executed after the return statement in a method.

In this case, once your handler returns a result, the scope changes and you programmatically can never reach code within that method after the return statement.

However, I suspect your question is more regarding ways to implement "fire and forget" endpoints, which do not block the consumer & make them wait for a response which they do not need at this moment in time.

That problem can be solved using asynchronous message queuing systems like RabbitMQ, Amazon SQS, Azure ASQs etc.

CodePudding user response:

You need to consider two things:

  • Obviously, no code will be executed after the return keyword
  • After returning response all objects with the lifetime of Transient and Scoped will be disposed

You can use the background task to execute your method after returning an immediate response. You can use:

Or check this question What is the simplest way to run a single background task from a controller in .NET Core?

CodePudding user response:

If you are using an asp.net core API template and I think that you are, the ControllerBase class that you inherited have CreatedAtRoute method that can run another API after returning 200 response like this :

return CreatedAtRoute("GetCustomer", new {CustomerName = Sajed} );
  • Related