大家好日子。我正在Visual Studio 2015中创建一个简单的Xamarin.Forms Portable Application。
我希望我的移动应用程序连接到我在VS2015中的SQL数据库,并返回一个应该显示在我的手机上的客户列表。
我创建了一个Xamarin Portable项目和一个WebForms项目,它将处理我的Web服务和数据库。
在我的WebForms项目中,我创建了一个应该返回客户列表的Controller。这有一个Web服务URL api / Customer ,我曾经在我的Xamarin Portable中连接到RestClient。我还有CustomerViewModel,它应该代表我的应用程序中的数据。
在我的Xamarin Portable项目中,我有一个ClientList.xaml,它应该显示来自我的数据库的List。我还有一个连接到Services和我的RestClient的CustomerVM。我的RestClient使用WEB SERVICE URL从我的WebForms项目中获取客户列表。
根据上面给出的步骤,我仍然无法在手机中显示数据。您认为这背后的原因是什么?谢谢你的帮助。
以下是我的一些代码:
RestClient.cs
() => void
CustomerServices.cs
public class RestClient_Customer<T>
{
private const string WebServiceUrl = "http://localhost:50857/api/Customer/";
public async Task<List<T>> GetCustomerAsync()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}
CustomerVM.cs
using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Services
{
public class CustomerServices
{
public async Task<List<Customer>> GetCustomerAsync()
{
RestClient_Customer<Customer> restClient = new RestClient_Customer<Customer>();
var customerList = await restClient.GetCustomerAsync(); //yung getasync ay pantawag as restclient
return customerList;
}
}
}
答案 0 :(得分:1)
我认为问题在于您的服务,希望这对您有所帮助,
public interface ICustomer
{
Task<string> GetCustomers();
}
public class CustomerService : ICustomer
{
public async Task<string> GetCustomers()
{
var client = new HttpClient();
var response = await client.GetAsync(string.Format("http://mysite/api/Customer"));
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
在任何你喜欢的地方打电话
var _custList = new GetCustomers();
var returnJson = await _custList.GetCustomers();
请注意,返回值是json字符串格式或xml格式,具体取决于您的REST API,因此您需要先解析它,然后才能获取值并将其显示到ListView
答案 1 :(得分:0)
尝试在UWP中运行它。如果它在UWP中有效,那么你必须看看 Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid
我遇到了同样的问题但是当我在UWP中尝试它时,它运行良好。我仍在寻找使用设备运行xamarin.android的解决方案。