Rest 将API密钥添加到WCF服务的标头以进行检查
我正在为我拥有的一个基本web服务实现一个api密钥。我正在使用一个在以下位置找到的实现: 我知道我已经在服务端正确地实现和设置了所有这些,但我不确定如何从我的客户端传递API密钥。当我根据请求调试web服务时,我没有得到任何关于HttpRequestMessage查询字符串的返回。以下是代码: Web服务身份验证管理器:Rest 将API密钥添加到WCF服务的标头以进行检查,rest,wcf,api-key,Rest,Wcf,Api Key,我正在为我拥有的一个基本web服务实现一个api密钥。我正在使用一个在以下位置找到的实现: 我知道我已经在服务端正确地实现和设置了所有这些,但我不确定如何从我的客户端传递API密钥。当我根据请求调试web服务时,我没有得到任何关于HttpRequestMessage查询字符串的返回。以下是代码: Web服务身份验证管理器: public string GetAPIKey(OperationContext oc) { // get the r
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];
}
客户消费(重要部分):
在调试期间,web服务总是在NameValueCollection中获取空queryParams,因为查询字符串为空。在客户端发出请求期间,如何向该查询字符串添加内容?已解决。解决方案是不尝试从HttpRequestMessageProperty.QueryString中提取,而只是从标题中提取 代码:
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));
}
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"];
}