【发布时间】:2017-05-24 22:01:13
【问题描述】:
我需要通过 UserName 和 Password 作为 header-key 来获取令牌。我在 Postman 中测试了 GET 方法,效果很好。但是我不能在我的 C# 代码中做同样的事情,因为我无法将 UserName 和 Password 作为标题键发送。
在我的代码中,我使用了PostAsync(参见代码),但它不起作用,因为无论如何(result.IsSuccessStatusCode) 总是false。所以我想我必须使用GetAsync 才能让它工作。但我不知道如何将UserName 和Password 作为标头值传递。
我的LoginVm 只包含UserName 和Password
public static async Task<Token> Authentication(LoginVm vm) {
Token token = null;
string requestJson = JsonConvert.SerializeObject(vm);
var client = new HttpClient();
//How to use GetAsync instead?
var result = client.PostAsync(new Uri("http://x.com/.../login"),
new StringContent(requestJson, Encoding.UTF8, "application/json")).Result;
if (result.IsSuccessStatusCode) {
string json = await result.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(json)) {
token = JsonConvert.DeserializeObject<Token>(json);
}
}
return token;
}
感谢所有帮助。
【问题讨论】:
-
你的方法是异步的,所以你可以用
var result = ().Result代替var result = await ()
标签: c# json visual-studio authentication xamarin