c# - 向 header 添加授权

标签 c# windows-phone-8 async-await dotnet-httpclient

我有以下代码:

...
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/

相关文章:

c# - 类型 Microsoft.OData.Edm.Date 和 System.Nullable System.DateTimeOffset 之间没有定义强制运算符

c# - Entity Framework 到 json - 分组数据

c# - 企业架构师 : C# Optional parameters?

c# - 在xaml中显示来自数据库的图片

jquery-mobile - 在 Xamarin 解决方案中使用 jQuery Mobile 是否可行?

c# - 未找到返回有效的 Azure 存储 URI

c# - nuget 无法在通用应用程序中将引用添加到 Windows Phone 8.1 项目中

javascript - vue.js 与 vuetify : Can't load google map in mounted

python - 如何在越来越多的任务上使用 asyncio.wait?

delay - .Net 4.5 和 Task.Yield vs Task.Delay 作为 DoEvents 的替代品?使用哪个?