我目前正在使用Spreedly REST API,它使用基本的http身份验证。
首先,我以这种方式设置我的凭据:
webRequest.Credentials = new System.Net.NetworkCredential(user, password);
它适用于许多API资源,包括POST新网关,GETing网关,在网关上PUTing数据甚至编辑网关。
当我尝试在/v1/payment_methods.<format>
资源上发布新的payment_method时,我碰壁了。
我得到的错误:
HTTP 422
{
"errors": [
{
"key": "errors.environment_key_parameter_required",
"message": "You must specify an environment_key parameter."
}
]
}
在验证了很多东西后,我根据他们的例子使用curl尝试了它并且它有效。
问题似乎与我在HttpWebRequest中设置我的凭据有关,即使它与我用于其他工作资源的代码相同。
我尝试使用CredentialCache,因为我可以指定“Basic”并且它以同样的方式失败:
CredentialCache cache = new CredentialCache();
cache.Add(webRequest.RequestUri, "Basic", new System.Net.NetworkCredential(user, password));
webRequest.Credentials = cache;
答案 0 :(得分:1)
我按https://stackoverflow.com/a/13956730/5869109中的建议创建了自己的授权HTTP标头,但效果很好:
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1")
.GetBytes(user + ":" + password));
webRequest.Headers.Add("Authorization", "Basic " + encoded);