Andreas Zita
Andreas Zita

Reputation: 7580

Async progress in ASP .NET Core middleware?

I have a web-api with mvc that's doing a bunch of startup initialization which will take a few minutes. I want the url to respond to a request during this time with a progress-indicator. My thinking was to use a middleware to accomplish this something like this:

public async Task Invoke(HttpContext httpContext)
{
  await httpContext.Response.WriteAsync("Loading...");

  await Task.Delay(5000); // the initialization-stuff (which is not started here but just waited on)

  httpContext.Response.Clear();

  await _next(httpContext); // continue to my MVC-page
}

However this does not seem to work (ERR_INCOMPLETE_CHUNKED_ENCODING). How do I properly clear/reset the respons so that I can write a new real response once the initialization is done.


I resorted to something like this instead (good enough):

public async Task Invoke(HttpContext httpContext)
{
  if (!task.IsCompleted)
    await httpContext.Response.WriteAsync("Loading...");
  else
    await _next(httpContext); // continue...
}

Upvotes: 1

Views: 1542

Answers (1)

usr
usr

Reputation: 171226

Once you have sent data to the client you can't take it back. You can't replace an existing page, only append.

You can therefore do two things:

  1. You delay the response until initialization is complete (likely not feasible).
  2. You send something else and end the request. You could make the page that you are sending poll the server using AJAX to see if initialization has been completed. Then, the page can reload itself.

Create a new API endpoint that replies with the initialization status. Make page page poll that endpoint every few seconds.

Upvotes: 1

Related Questions