我有一个WPF应用程序,我用它来从Web API中提取数据。
登录后,我存储令牌,并根据您可以访问API。
案例1:登录,获取令牌,点击按钮获取数据:
private async void button1_Click(object sender, RoutedEventArgs e)
{
getMovies();
}
实施方法
private void getMovies()
{
var accessToken = token;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri("http://localhost:5001/movies/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("get").Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show(response.Content.ReadAsStringAsync().Result);
}
else
{
MessageBox.Show("Movies not Found");
}
}
我收到了401。
案例2:我从Start方法调用API(与上面相同的代码):从API获取数据
public async void Start(object sender, RoutedEventArgs e)
{
getMovies();
}
这怎么可能?如何在Start
方法之外访问我的API?
答案 0 :(得分:1)
首先应该重构该方法以遵循通常建议的语法
string baseUrl = "http://localhost:5001/movies/"
private async Task getMoviesAsync() {
var accessToken = token; //assuming token is being retrieved and set somewhere else
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("get");
if (response.IsSuccessStatusCode) {
MessageBox.Show( await response.Content.ReadAsStringAsync());
} else {
MessageBox.Show("Movies not Found");
}
}
并调用如下
private async void button1_Click(object sender, RoutedEventArgs e) {
await getMoviesAsync();
}
通常不建议在永远调用时创建HttpClient
,但这对于当前的问题来说是偏离主题的。