【发布时间】: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,因为查询字符串为空。如何在客户端发出请求期间添加到该查询字符串?
【问题讨论】: