views:

229

answers:

3

As part of a suite of integration tests I am writing, I want to assert that my server behaves correctly when a client HTTP request terminates early, before all the response data has been sent.

Is it possible to create an HTTP request and terminate it after receiving just a few bytes of data in C#?

A: 

Just start the call asynchronously using, say a background worker, and then close the thread/channel.

Preet Sangha
You don't need a thread/bgworker. If you want to do it asynchronously, You can use WebRequest's BeginGetResponse and EndGetResponse methods: http://msdn.microsoft.com/en-us/library/86wf6409.aspx
Ravi
+2  A: 

You don't have to read all bytes out fo the response. Just read as many bytes as you want and then return from your test.

You can do so more or less like this:

Stream myStream = resp.GetResponseStream();
myStream.Read(bufferArray, 0, 1); //read 1 byte into bufferArray
return;

You may find the documentation on WebReponse useful.

Esteban Araya
Yep, that works pretty well for me! Although in my case I don't care about any specific response data, so just close the stream without reading any.
Karl
@Karl, You're right; make sure you dipose the reponse correctly.
Esteban Araya
A: 

I found a solution which works for me. I just close the response after getting it. This seems to leave me with the response headers, but closes the connection before the server is finished sending.

var response = request.getResponse();
response.Close();

// Assert that server has dealt with closed response correctly
Karl