c# - 如何在 RestSharp 中使用 ExecuteAsync 返回变量
问题描述
我在异步方法中返回变量时遇到问题。我能够让代码执行,但我无法让代码返回电子邮件地址。
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# 中类的好名称。我们通常的约定是 PascalCase 类名,所以它应该是 RootUser。
推荐阅读
- assembly - 将值从寄存器存储到内存中的问题,ARM 32位
- css - 样式化的组件填充 MUI 网格内的 div 高度
- linux-kernel - IOMMU 如何通过 DMA 取消映射来自不同外设的 IOVA
- sms - 华为 Cdma 调制解调器,如何通过 C# App 或 AT 命令发送短信
- python - Django模型中的类关系
- android - 网格布局在不同手机上的工作方式不同
- reactjs - 使用 onClick 传递值并使用钩子更新两个状态值
- python - 有没有更优雅的方法可以在 Python 中创建任意字典的修改副本?
- javascript - 如何使用按钮进行加、乘和减
- javascript - 在引导程序中将输入标签与 div 元素内的底部对齐