Persistent HTTP Connection with RestSharp

Adam Cobb picture Adam Cobb · Jun 11, 2012 · Viewed 9.4k times · Source

I am using RestSharp to consume a REST web service and will be making a large volume of calls in a short time period.

The documentation for the API strongly recommends the use of persistent HTTP connections to do this, however I am struggling to get this working with RestSharp.

I have tried adding the "Connection: Keep-alive" header to the request but when I do this the request fails with the following error - "Keep-Alive and Close may not be set using this property."

Can I not use this header with RestSharp or is there something else I need to do to enable this?

Can anyone help? Thanks.

Answer

BenSwayne picture BenSwayne · Jun 19, 2012

To get a good answer, you need to ask a good question. Where in the documentation does it say this? (Link/Reference?) How many requests is a "large volume"? Also, if you post your code for how you added Connection: Keep-Alive to your http headers, someone here may be able to comment on your technique and help you with the specific programming issue.

Also, Connection: Keep-Alive may already be present on the outgoing HttpRequests! Check it out using Fiddler or WireShark. I've seen a few blog posts with wireshark captures of RestSharp requests that had the Connection: Keep-Alive header present without any extra config. For example, while testing other mvc3 functionality using RestSharp as a consumer, Jimmy Bogard captures his RestSharp requests with fiddler which already have the Connection: Keep-Alive header.

Apparently it is also the default behavior for built in .Net classes like System.Net.Webclient to use Connection: Keep-Alive. Reference Does WebClient use KeepAlive?

I think that making use of keep alive is going to be more about your code using RestSharp in an optimal manner than it is about configuring RestSharp itself. If you want to make sure your connection is reused you need to make sure your use of RestSharp allows for that by keeping one RestClient instance in scope and reusing it throughout multiple requests against the same host.

Again using Fiddler or WireShark will help you capture some HttpRequests for analysis.