[英]Consuming a Web API in Xamarin
I've created a Web API in ASP.NET that is hosted on a web server. 我已经在Web服务器上托管的ASP.NET中创建了Web API。 This Web API accesses a table in SQL Server where I have a table called
Products
with Id, ProductName, Description and Price
, I did the tests via Postman and it is working correctly, but when I try to consume the method to bring a specific product via Xamarin application, I get the following error message in break mode: 该Web API访问SQL Server中的一个表,其中有一个名为
Id, ProductName, Description and Price
Products
表,我通过Postman进行了测试,并且工作正常,但是当我尝试使用该方法带来特定产品时通过Xamarin应用程序,我在中断模式下收到以下错误消息:
System.Net.Http.HttpRequestException: Timeout exceeded getting exception details
System.Net.Http.HttpRequestException:超时超过了获取异常详细信息
public class DataService
{
public async Task<List<Product>> GetProductAsync(string ProductName)
{
using (var client = new HttpClient())
{
string url = "http://ProductsAPI.hostname.com/api";
try
{
var uri = url + "/" + ProductName.ToString();
HttpResponseMessage response = await client.GetAsync(uri);
var ProductJsonString = awaitresponse.Content.ReadAsStringAsync();
var Product = JsonConvert.DeserializeObject<List<Product>>(ProductJsonString);
return Product;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Here's what I've used in the past: 这是我过去使用的:
public string GetAPIJsonAsync(string URL)
{
using (WebClient wc = new WebClient())
{
return wc.DownloadString(URL);
}
}
This would return the raw JSON to whoever called it, and I would then convert it to the desirable object. 这会将原始JSON返回给任何调用它的人,然后我将其转换为所需的对象。
This Works Perfectly for me 这完全适合我
public static async Task<List<BranchMasterModel>> GetBranchList(int city)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);//("http://192.168.101.119:8475/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "AuthToken"));
var result = await client.GetAsync("api/Master/V2/Branch/"+city);
string branch = await result.Content.ReadAsStringAsync();
var branches = JsonConvert.DeserializeObject<List<BranchMasterModel>>(branch);
return branches;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.