我有以下代码:
...
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("OAuth2", Contract.AccessToken);
string result = await PostRequest.AuthenticatedGetData(fullUrl, null, authHeaders);
return result;
...
public static async Task<string> AuthenticatedGetData(string url, FormUrlEncodedContent data, AuthenticationHeaderValue authValue)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue.Parameter);
HttpResponseMessage response = await client.PostAsync(new Uri(url), data);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
response = await部分只是继续一个正在进行的循环,什么也不会发生。你知道我做错了什么吗?
真正的问题是,我如何发送以下标头:
Authorization: OAuth2 ACCESS_TOKEN
添加到外部web api
发布于 2013-09-27 06:45:53
这一行
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(authValue.Parameter);
将生成此标头值
Authorization: ACCESS_TOKEN
其中ACCESS_TOKEN
是authValue.Parameter
的值。您希望将传递的值赋值,以获取所需的标头
client.DefaultRequestHeaders.Authorization = authValue;
将产生
Authorization: OAuth2 ACCESS_TOKEN
发布于 2014-07-04 21:43:08
我为此而苦苦挣扎。我一直收到“无效格式”的错误,因为我有一个自定义的实现,Authorization头是根据某些标准进行验证的。但是,以这种方式添加头文件是可行的:
var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");
发布于 2017-12-21 03:57:42
在让AuthenticationHeaderValue处理我的请求时也遇到了类似的问题。我也在使用来自GitHub的JWT JsonWebToken。我能够从API中获得一个令牌,但在其他get和POST中使用它是很困难的。
var jwt = JsonWebToken.Encode(token, APISECRET, JwtHashAlgorithm.HS256);
var tk = GetTokenFromApi(); // basically returns an encrypted string.
手动使用WebRequest:工作得很好。
request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Set("Authorization", string.Format("Bearer {0}", tk));
当我们切换到HttpClient并使用AuthenticationHeaderValue时,在查看请求字符串时,我不知道如何设置它,我看到它为我添加了“correctly.After”。试着使用参数,这最终起作用了。
var authenticationHeaderValue = new AuthenticationHeaderValue("Bearer", tk);
https://stackoverflow.com/questions/19039450
复制相似问题