简体   繁体   English

Xamarin.Forms中的HTTP请求

[英]HTTP Request in Xamarin.Forms

I'm building a Xamarin.Forms App for Android and iOS which is supposed to consume an API. 我正在为Android和iOS开发一个Xamarin.Forms应用程序,该应用程序应该使用API​​。 The API is kind of built in a REST spirit, I'm hosting the API on a local IIS Express server and my Android emulator has no problem finding it (tested on various endpoints and I can also display the api-doc). 该API是基于REST精神构建的,我将API托管在本地IIS Express服务器上,而我的Android模拟器可以毫无问题地找到它(在各种端点上进行了测试,并且我还可以显示api-doc)。 I'm trying to get in touch with a http://IPOfMyComputer/api/Stuffs endpoint which gives me a JSON list of Stuff. 我正在尝试与http://IPOfMyComputer/api/Stuffs端点联系,该端点为我提供了Stuff的JSON列表。 Using Postman I successfully get all the stuff I needed, a valid auth token in that case, to build a proper HTTP GET request. 使用Postman,我成功获取了我需要的所有东西,在这种情况下是有效的auth令牌,以建立正确的HTTP GET请求。 I'm using the Microsoft.Net.Http NuGet package to build this request as it seemed to be the proper tool to do the job. 我正在使用Microsoft.Net.Http NuGet包来生成此请求,因为它似乎是完成此工作的适当工具。 I'm doing this request building process in Xamarin.Forms "Main" project (not the iOS or Android one, the other one which I don't know how to name which is automatically by Visual Studio). 我正在Xamarin.Forms“主要”项目(不是iOS或Android,另一个是我不知道如何由Visual Studio自动命名的项目)中进行此请求构建过程。

My code looks like this: 我的代码如下所示:

var rootUri = "http://IPOfMyComputer"
var requestedUri = "/api/Stuffs"
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 
"blablabla");
var response = await client.GetAsync(rootUri + requestedUri);

And this gives me an error "NotSupportedException" on the last instruction. 这给了我最后一条指令一个错误“ NotSupportedException”。 I'm clueless here so some help would be really appreciated. 我在这里一无所知,所以将不胜感激。
Edit 编辑
The proper error message is "System.InvalidCastException: Specified cast is not valid." 正确的错误消息是“ System.InvalidCastException:指定的转换无效。”

I found the source of that error: 我发现了该错误的来源:
Turns out it wasn't directly linked with the GetAsync method but with some mess in the code related with async/await use. 事实证明,它不是直接与GetAsync方法链接,而是与异步/等待使用相关的代码有些混乱。
There was a bunch of crappy code everywhere. 到处都有一堆糟糕的代码。 I dropped it all to go back to a regular MVVM logic and I put the async/await logic into methods invoked by eventhandlers (instead of trying to "create" an async builder for a class...). 我将所有内容放回常规的MVVM逻辑,并将异步/等待逻辑放入事件处理程序调用的方法中(而不是尝试“为类创建”异步生成器...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM