【问题标题】:Adding API key to header for WCF service to check将 API 密钥添加到 WCF 服务的标头以进行检查
【发布时间】:2017-12-27 19:05:40
【问题描述】:

我正在为我拥有的基本 Web 服务实现一个 api 密钥。我正在使用在这里找到的实现:https://blogs.msdn.microsoft.com/rjacobs/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4/ 我知道我已经在服务端正确实现和设置了它,但我不确定如何从我的客户端传递 API 密钥。当我根据请求调试 Web 服务时,我的 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));
            }

在调试期间,Web 服务总是在 NameValueCollection 中获取空的 queryParams,因为查询字符串为空。如何在客户端发出请求期间添加到该查询字符串?

【问题讨论】:

    标签: rest wcf api-key


    【解决方案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"];
            }
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多