2

I have an ASP Core app that basically acts as a proxy

public IActionResult PostFileRequest(IFormFile file)
{
    var httpRequest = new HttpRequestMessage()
    {
        Content = new StreamContent(file.OpenReadStream())
    };
    var task = httpClient.SendAsync(httpRequest);

    // we store the task internally to be later processed by background services
    // we don't want the user to wait for the response

    return Ok();
}

The problem with this logic is that the user can get the response even before the httpRequest is sent. The file stream gets disposed, and I get the exception. I do not want the client to wait for the response. Is there some separate Task that completes when HttpClient finishes sending the request? After the file is sent I don't need the stream anymore, and can safely answer the user and close the context.

UPD: in case the comment in the code was not clear enough: no, I do not ignore the result of SendAsync. I process it in the background service. But the response to the user will always be the same regardless of the result, so the task here is to answer to the user and release the context as soon as possible.

Morse
  • 1,330
  • 2
  • 17
  • 27
  • How would this be useful? Until there is some response, there are no guarantees that the message has been received. – Johnathan Barclay Oct 20 '20 at 12:05
  • I know it's a SO cliche, but it sounds like you've got a slightly more fundamental logical flaw... You're fire-and-forgetting an HTTP request without any idea if it was received. Seems like a recipe for disaster later down the line, if not now. – WSC Oct 20 '20 at 12:06
  • I'm not forgetting the request, I'm saving it and processing it in the background. It's just that I want to send the response to the user as soon as possible. I.e. as soon as httpClient is done with the file stream. – Morse Oct 20 '20 at 12:47
  • 1
    Initiating the request in the controller might lead do some DI issue since you're relying on objects going past the lifetime of their scope. A possible solution would be to copy the stream somewhere as part of the request and push it down to a background service, similar to https://stackoverflow.com/questions/49813628/run-a-background-task-from-a-controller-action-in-asp-net-core-2 – ESG Oct 20 '20 at 13:03

0 Answers0