Detecting Request Cancellation From IStreamWriter


I’m building a custom HttpResult designed to stream content to the browser.

In my case I’m working with video, so I’m taking content from a file, sending bytes from that file into FFMPEG and then reading bytes from STDOUT and streaming them back to the responseStream.

Because transcoding video takes time I want to detect when a user has canceled a request and kill the executable. At present I’m doing this by listening for exceptions when writing to the responseStream.

It appears to be throw this:

System.Net.HttpListenerException (0x80004005): An operation was attempted on a nonexistent network connection

Is this the best way to detect a request cancellation in this context?

Many thanks!


There’s no standard way for detecting that a User has terminated their underlying TCP connections which is Host specific, whilst HttpListener self-hosts may throw this Exception, there’s no way to detect it in ASP.NET which doesn’t throw any Exception.

We do have a Cancellable Request Feature that provides a generic mechanism for a client to cancel a server operation, but this requires the client to explicitly notify they want to cancel a running Service.