我正在为我的基本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查询字符串返回任何内容。这是代码:
Web服务验证管理员:
> Q:\Test\2017\07\21\SO_45239319.ps1
dir metadata_name metadata_file config_file
--- ------------- ------------- -----------
wordone secondword thridword fourthword
wordone1 secondword1 thridword1 fourthword1
wordone2 secondword2 thridword2 fourthword2
----
config_file is fourthword checking wordone.xml
config_file is fourthword1 checking wordone1.xml
config_file is fourthword2 checking wordone2.xml
客户消费(重要的部分):
-WhatIf
在调试期间,Web服务始终在NameValueCollection中获取空queryParams,因为查询字符串为空。如何在客户端发出请求期间添加到该查询字符串?
答案 0 :(得分:0)
解决。解决方案是不要尝试从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"];
}