gpt4 book ai didi

c# - 使用身份验证 token 的 REST 调用

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:29 25 4
gpt4 key购买 nike

我在 XAML 应用程序上编写了这个简单的调用来尝试调用 REST 服务。

该程序似乎可以正常工作,但我在使用异步方法时遇到问题...我在 fiddler 上看到我收到了 token ,但该程序没有注意到。

我该如何解决?是否有最佳做法可以做到这一点?

这是文件 xaml.cs 的隐藏代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;


namespace CallRESTToken
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button_Click(object sender, RoutedEventArgs e)
{
try
{
const string userName = "user";
const string password = "password";
const string apiBaseUri = "http://example.com";
const string apiGetPeoplePath = "/api/values";


//Get the token
var token = GetAPIToken(userName, password, apiBaseUri).Result;

textBoxtoken.Text = (token);

//Console.WriteLine("Token: {0}", token);

//Make the call
var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result;

textBox1view.Text = (response);
//Console.WriteLine("response: {0}", response);

//wait for key press to exit
//Console.ReadKey();
}
catch (Exception ex)
{

throw ex;
}
}

private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
{
try
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
});

//send request
HttpResponseMessage responseMessage = await client.PostAsync("/token", formContent);

//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
return jObject.GetValue("access_token").ToString();
}

}
catch (Exception ex)
{

throw ex;
}

}

static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
{
try
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

//make request
HttpResponseMessage response = await client.GetAsync(requestPath);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
catch (Exception ex)
{

throw ex;
}
}
}
}

最佳答案

您将 async.Result 阻塞调用混合在一起。

更新事件处理程序以使用异步/等待并删除 .Result 阻塞调用。事件处理程序是允许 async void

的豁免情况
private async void button_Click(object sender, RoutedEventArgs e) {
try {

//... code removed for brevity

//Get the token
var token = await GetAPIToken(userName, password, apiBaseUri);

//... code removed for brevity

//Make the call
var response = await GetRequest(token, apiBaseUri, apiGetPeoplePath);

//... code removed for brevity

} catch (Exception ex) {
throw ex;
}
}

阅读Async/Await - Best Practices in Asynchronous Programming

关于c# - 使用身份验证 token 的 REST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42192092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com