如何在 RestSharp 中使用 ExecuteAsync 到 return 变量
How to Use ExecuteAsync in RestSharp to return variable
我在 return 在我的异步方法中设置变量时遇到问题。我能够让代码执行,但我无法将代码发送到 return 电子邮件地址。
public async Task<string> GetSignInName (string id)
{
RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
RestRequest request = new RestRequest($"{id}");
request.AddParameter("api-version", "1.6");
request.AddHeader("Authorization", $"Bearer {token}");
//string emailAddress = await client.ExecuteAsync<rootUser>(request, callback);
var asyncHandler = client.ExecuteAsync<rootUser>(request, response =>
{
CallBack(response.Data.SignInNames);
});
return "test"; //should be a variable
}
RestSharp 内置了执行基于任务的异步模式 (TAP) 的方法。这是通过 RestClient.ExecuteTaskAsync<T>
方法调用的。这会给你一个回应,并且 response.Data
属性 将有你的通用参数的反序列化版本(在你的例子中是 rootUser)。
public async Task<string> GetSignInName (string id)
{
RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
RestRequest request = new RestRequest($"{id}");
request.AddParameter("api-version", "1.6");
request.AddHeader("Authorization", $"Bearer {token}");
var response = await client.ExecuteTaskAsync<rootUser>(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response from Windows Graph API. Check inner details for more info.";
var exception = new Exception(message, response.ErrorException);
throw exception;
}
return response.Data.Username;
}
请注意,rootUser
不是 C# 中 class 的好名称。我们的常规约定是 PascalCase class 名称,因此它应该是 RootUser.
我在 return 在我的异步方法中设置变量时遇到问题。我能够让代码执行,但我无法将代码发送到 return 电子邮件地址。
public async Task<string> GetSignInName (string id)
{
RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
RestRequest request = new RestRequest($"{id}");
request.AddParameter("api-version", "1.6");
request.AddHeader("Authorization", $"Bearer {token}");
//string emailAddress = await client.ExecuteAsync<rootUser>(request, callback);
var asyncHandler = client.ExecuteAsync<rootUser>(request, response =>
{
CallBack(response.Data.SignInNames);
});
return "test"; //should be a variable
}
RestSharp 内置了执行基于任务的异步模式 (TAP) 的方法。这是通过 RestClient.ExecuteTaskAsync<T>
方法调用的。这会给你一个回应,并且 response.Data
属性 将有你的通用参数的反序列化版本(在你的例子中是 rootUser)。
public async Task<string> GetSignInName (string id)
{
RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
RestRequest request = new RestRequest($"{id}");
request.AddParameter("api-version", "1.6");
request.AddHeader("Authorization", $"Bearer {token}");
var response = await client.ExecuteTaskAsync<rootUser>(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response from Windows Graph API. Check inner details for more info.";
var exception = new Exception(message, response.ErrorException);
throw exception;
}
return response.Data.Username;
}
请注意,rootUser
不是 C# 中 class 的好名称。我们的常规约定是 PascalCase class 名称,因此它应该是 RootUser.