我有以下代码:
...
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 部分只是继续一个正在进行的循环,没有任何反应。知道我做错了什么吗?
真正的问题是,我如何发送以下 header :
Authorization: OAuth2 ACCESS_TOKEN
到外部 web api
最佳答案
我为此苦苦挣扎。我一直收到一条错误消息,说“格式无效”,因为我有一个自定义实现,并且 Authorization header 已根据某些标准进行了验证。但是,以这种方式添加 header 有效:
var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");
关于c# - 向 header 添加授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039450/