xamarin - 如何从 Xamarin 中的 WebAPI 获取结果值
问题描述
public async Task<Customer> GetCustomersAsync(string id)
{
var prod = new Customer();
HttpClient client = new HttpClient();
string url = "https://xxxxxx.com/api/Customers/" + id;
client.BaseAddress = new Uri(url);
HttpResponseMessage response = await client.GetAsync("");
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
prod = JsonConvert.DeserializeObject<Customer>(content);
}
return await Task.FromResult(prod);
}
类客户(型号)
public class Customer { public string CodeRandom { get; set; } public string NameUs { get; set; } }
我确实调用了 API 以获取结果。但是当我无法得到返回结果时.Result
我就是这样做的:
var infocustomer = customerRepository.GetCustomersAsync(userrating);
string nameus = infocustomer.Result.NameUs;
- 当我调试时,
nameus
它会自行退出。请给我任何解决方案。谢谢
解决方案
而不是这个
string content = response.Content.ReadAsStringAsync().Result;
做这个
string content = await response.Content.ReadAsStringAsync();
然后就
return prod;
推荐阅读
- c++ - 在 C++ 中,为什么我们必须在复制构造函数中传递用户定义的数据类型作为引用而不是在函数中,反之亦然?
- r - 在 R 中编写一个使用向量运算的函数,以便将其应用于向量
- spring-batch - Spring Batch - 如何将标题信息保存到 FlaFileItemReader 中的单个行对象中
- python - 如何再添加一个频道 ID,以便机器人对更多频道做出反应?
- python - 在 Tkinter 的文件夹中动态初始化 Frames
- java - 从 javafx 中的 Stage 类创建新对象时抛出异常
- latex - 更改 LaTex 中的附录格式
- javascript - moment.js 返回 "NaN" for moment("03/13/2020", "YYYY-MM-DD")
- c++ - 如何使用父类指针中未在父类中定义的子类方法?
- c# - 将多页 TIFF 拆分为多个 JPG 文件