1

How can I return multiple values from Http method dynamically as progress ?

I have tried method :

public async IAsyncEnumerable<IActionResult> GenerateImage(){
CancellationToken cancellationToken = _httpContextAccessor.HttpContext.RequestAborted;

await Task.Factory.StartNew(() =>
  {
      for(int i =0; i< 10; i++)
      {
         Ok(new {id = i });
         Thread.Sleep(1000);
         if (cancellationToken.IsCancellationRequested)
         {
              Ok("Cancel requested");
              break;
         }
       }   
     }, cancellationToken);
            yield return Ok();
}

Question : Can I somehow make Http method return 'i' one by one to track progress ?

Cancelation token works (Angular side) - when on cancel button click => this.subscription.unsubscribe();

Additional Information : I am using Angular 11 project for front-end and Web API built on .NET 5

JmukhadzeT
  • 99
  • 1
  • 9
  • You have a controller that is return a list of classes which is IActionResult. A deserialize method is used to take the response and convert to the class object IActionResult. You can add an ID to the class structure and then have the server code write the ID before sending the response. – jdweng Jan 24 '22 at 10:49
  • 2
    You can't. Think about it, You make a request, via http, then you receive a http Response from the API and the comunication closes. If you're trying to get a set of records, You can paginate the results, and send another request for next pages of results, but not exactly what you want – J.Salas Jan 24 '22 at 10:56
  • (This is Dummy example of my method ) Actually I am starting Image generation process running on background (lets say 100 images) when this endpoint is called and I want to report back process after each image has been created. Can I achieve that or not ? I thought it might be done using yield return – JmukhadzeT Jan 24 '22 at 11:00
  • 2
    No, after the web API replies with a Http response all comunication is closed. You can start the process and save some processID & processState in a serverside database, update every image is processed and build another method in webApi to check the state – J.Salas Jan 24 '22 at 11:18
  • 1
    @JmukhadzeT Does this answer your question: https://stackoverflow.com/a/64983795/13268855 ? – Peter Csala Jan 24 '22 at 11:38
  • @PeterCsala Yes , thanks – JmukhadzeT Jan 24 '22 at 12:08
  • 1
    @JmukhadzeT Awesome. I've marked your question as a duplicate. If you have found my post useful then please consider to upvote it. Have a nice day! – Peter Csala Jan 24 '22 at 12:12

0 Answers0