Adding API key to header for WCF service to check

Viewed 1748

I am implementing an api key for a basic web service I have. I am using an implementation found here: https://blogs.msdn.microsoft.com/rjacobs/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4/ I know I have it all implemented and setup correctly on the service side but I am not sure how to pass the API key from my client. When I debug the web service upon request I don't get anything returned for my HttpRequestMessage query string. Here is code:

Web service auth manager:

        public string GetAPIKey(OperationContext oc)
        {
            // get the request
            var request = oc.RequestContext.RequestMessage;
            // get HTTP request message
            var requestProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
            // get the actual query string
            NameValueCollection queryParams = HttpUtility.ParseQueryString(requestProp.QueryString);

            // return APIKey if there, NameValueCollection returns null if not present
            return queryParams[APIKEY];
        }

Client consumption (the part that matters):

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("APIKey","my_generated_key");
                client.Encoding = Encoding.UTF8;
                Console.WriteLine(client.UploadString("http://my_local_host/my.svc/myCall", "POST", data));
            }

During debug, the web service is always getting empty queryParams in the NameValueCollection because the query string is empty. How do I add to that query string during the request made from the client?

1 Answers
Related