Search code examples
asp.net-coreasp.net-web-apihttp-status-codes

ASP.NET Core and 102 status code implementation


I have long operation, which called via Web API. Status code 102 says to us:

An interim response used to inform the client that the server has accepted the complete request, but has not yet completed it.

This status code SHOULD only be sent when the server has a reasonable expectation that the request will take significant time to complete. As guidance, if a method is taking longer than 20 seconds (a reasonable, but arbitrary value) to process the server SHOULD return a 102 (Processing) response. The server MUST send a final response after the request has been completed.

So, I want to return 102 status code to client, then client waits response about result of operation. How to implement it on .NET?

I read this thread: How To Return Http 102 Processing in Asp.Net Web Api?

This thread has good explanation what is necessary, but no response. I don't understand how it implement on .NET, not theory...


Solution

  • Using HTTP 102 requires that the server send two responses for one request. ASP.NET (Core or not) does not support sending a response to the client without completely ending the request. Any attempt to send two responses will end up in throwing an exception and just not working. (I tried a couple different ways)

    There's a good discussion here about how it's not actually in the HTTP spec, so implementing it isn't really required.

    There are a couple alternatives I can think of:

    1. Use web sockets (a persistent connection that allows data to be sent back and forth), like with SignalR, for example.
    2. If your request takes a long time because it's getting data from elsewhere, you can try pulling in that data via a stream and send it to the client via a stream. That will send the data as it's coming in, rather than loading it all into memory first before sending it. Here's an example of streaming data from a database to the response: https://stackoverflow.com/a/45682190/1202807