This project is read-only.

Automatically added query string parameters

Topics: Web Api
Feb 2, 2011 at 9:56 PM

Good day,

We may need to consume an API that requires an "API key" to be supplied as a query string parameter on each HTTP request. Is there any way to configure HttpClient to automatically inject that query string parameter for each request that it does? If not, is this something that could be added?

Something like:

HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1048576 };

client.AddParameter(ParameterType.QueryString, "api_key", apiKeyValue);

// Now every .Get, .Post, etc. done through 'client' will have '?api_key=value' automatically appended to the supplied URI fragment.


Jonathan Gilbert

Feb 2, 2011 at 11:44 PM
Edited Feb 3, 2011 at 12:13 AM

Create a class like this

    public class AuthenticatingWebRequestChannel : WebRequestChannel {
        protected override HttpResponseMessage Send(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {

            request.RequestUri = AddApiKey(request.RequestUri);
            return base.Send(request, cancellationToken);
and then attach an instance of it to your HttpClient like this
httpClient.Channel = new AuthenticatingWebRequestChannel();

I'll leave the AddApiKey for you to do :-)
Feb 3, 2011 at 3:08 PM

Ah, perfect :-) Thanks!