Добавление ключа API в заголовок для проверки службы WCF

Я реализую ключ API для базового веб-сервиса, который у меня есть. Я использую реализацию, найденную здесь: https://blogs.msdn.microsoft.com/rjacobs/2010/06/14/how-to-do-api-key-verification-for-rest-services.-in-net-4/ Я знаю, что все это реализовано и правильно настроено на стороне службы, но я не уверен, как передать ключ API от моего клиента. Когда я отлаживаю веб-службу по запросу, я ничего не возвращаю для своей строки запроса HttpRequestMessage. Вот код:

Диспетчер аутентификации веб-сервиса:

        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];
        }

Потребление клиентов (часть, которая имеет значение):

            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));
            }

Во время отладки веб-служба всегда получает пустые параметры запроса в коллекции NameValueCollection, поскольку строка запроса пуста. Как добавить к этой строке запроса во время запроса от клиента?


person CodySig    schedule 21.07.2017    source источник


Ответы (1)


Решено. Решение состояло в том, чтобы не пытаться извлекать из HttpRequestMessageProprty.QueryString, а просто извлекать из заголовков.

Код:

        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 = requestProp.Headers;

            // return APIKey if there, NameValueCollection returns null if not present
            return queryParams["APIKey"];
        }
person CodySig    schedule 21.07.2017