Force connection to close with HttpClient in WCF

2019-08-28 03:37发布

问题:

We're using the HttpClient class from "Rest toolkit" for WCF ( http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644 ) to inteface a Rest-server we've created.

The server currently always close the connection, regardless of the "connection" header (it is in developement, so that is ok for now).

How can I tell the HttpClient instance to always close the connection (or accept that the server closes it)? I tried adding the " Connection: close" header, but resulted in an exeption ("connection" was not an allowed header). I also tried to set DefaultHeaders.Connection.Close = true, but this didn't seem to make any difference. I can still see the connection with netstat after the POST is done.

(body and uri are strings)

HttpClient client = new HttpClient();
client.DefaultHeaders.Connection = new Connection();
client.DefaultHeaders.Connection.Close = true;
HttpContent content = HttpContent.Create(body);
HttpResponseMessage res = client.Post(new Uri(uri), content);

The problem here is that the next time we do a POST, the call just blocks. We think this is due to the fact that the connection is kept alive by the client, and this is not supported by the server.

回答1:

I wrote most of the HttpClient code; here are some thoughts:

You don't need to tell HttpClient to accept the server closing the connection -- it should just work automatically -- the server can always close the connection whether or not the client includes the "Connection: close" header

Use response.Dispose() -- the underlying connection may not be able to initiate a new connection / send bytes until you're done reading the bytes that are pending

client.DefaultHeaders.Add("Connection", "close"); should work -- if you get an exception, please open an issue on the codeplex site

You can inspect response.Request.Headers to see what's going out on the wire

You can skip the "new Uri()" in Post(new Uri(x)) -- passing a string will call the right constructor (new Uri(x, UriKind.RelativeOrAbsolute)) for you

By default, the timeouts are the same as HttpWebRequest -- you might want to turn them down via client.TransportSettings.ReadWriteTimeout / client.TransportSettings.ConnectionTimeout to distinguish between blocking forever and timing out



回答2:

Have you tried disposing the response when you're done with it?

// do stuff
res.Dispose();

or

using (HttpResponseMessage res = client.Post(new Uri(uri), content))
{
    // do stuff
}


标签: c# wcf http rest