简体   繁体   English

Xamarin.Forms连接到Web服务

[英]Xamarin.Forms Connecting to Web Services

Good Day Everyone. 今天是个好日子。 I'm creating a simple Xamarin.Forms Portable Application in my Visual Studio 2015. 我正在Visual Studio 2015中创建一个简单的Xamarin.Forms可移植应用程序。

I want my Mobile Application to connect to the SQL Database I have in my VS2015 and return a LIST OF CUSTOMERS which should be display to my mobile phone. 我希望我的移动应用程序连接到我在VS2015中拥有的SQL数据库,并返回客户列表,该列表应显示在我的手机上。

I have created a Xamarin Portable project and a WebForms project that will handle my Web Services and Database. 我创建了一个Xamarin Portable项目和一个WebForms项目,它们将处理我的Web服务和数据库。

In my WebForms project, I created a Controller that should return the List of Customers. 在我的WebForms项目中,我创建了一个控制器,该控制器应返回客户列表。 This has a web service URL api/Customer that I used to connect to the RestClient in my Xamarin Portable. 它具有一个Web服务URL api /客户 ,我用来连接到Xamarin Portable中的RestClient。 I also have CustomerViewModel that should represent the data in my application. 我也有CustomerViewModel应该代表我的应用程序中的数据。

In my Xamarin Portable project, I have a ClientList.xaml that should display the List that comes from my database. 在我的Xamarin Portable项目中,我有一个ClientList.xaml,它应该显示来自数据库的列表。 I also have a CustomerVM that is connected to Services and my RestClient. 我也有一个CustomerVM,它已连接到Services和我的RestClient。 My RestClient used the WEB SERVICE URL to get the List of Customer from my WebForms project. 我的RestClient使用Web服务URL从我的WebForms项目中获取客户列表。

Based on the given steps above, I still wasn't able to display the Data in my mobile phone. 根据上述给定的步骤,我仍然无法在手机中显示数据。 What do you think is the reason behind this? 您认为这背后的原因是什么? Thanks for your help. 谢谢你的帮助。

Here are some of my codes: 这是我的一些代码:

RestClient.cs RestClient.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;
   }
 }

CustomerServices.cs CustomerServices.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;
        }
    }
}

CustomerVM.cs CustomerVM.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
using XamarinFormsDemo.Views;

namespace XamarinFormsDemo.ViewModels
{
    public class CustomerVM : INotifyPropertyChanged
    {


        private List<Customer> _customerList; // keep all customers
        private List<Customer> _searchedCustomerList; // keep a copy for searching
        private Customer _selectedCustomer = new Customer();

        private string _keyword = "";
        public string Keyword
        {
            get
            {
                return _keyword;
            }
            set
            {
                this._keyword = value;

                // while keyword changed we filter Employees
                //Filter();
            }
        }



        private void Filter()
        {
            if (string.IsNullOrWhiteSpace(_keyword))
            {
                CustomerList = _searchedCustomerList;

            }
            else
            {
                // var lowerKeyword = _keyword.ToLower();
                CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList();
                //  EmployeesList = _searchedEmployeesList.Where(r => r.EMPLOYEE_NAME.Contains(_keyword)).ToList();


            }
        }


        public List<Customer> CustomerList
        {
            get
            {
                return _customerList;
            }
            set
            {
                _customerList = value;
                OnPropertyChanged();
            }
        }



        public CustomerVM()
        {
            InitializeDataAsync();

        }

        private async Task InitializeDataAsync()
        {
            var customerServices = new CustomerServices();
            _searchedCustomerList = await customerServices.GetCustomerAsync();
            CustomerList = await customerServices.GetCustomerAsync();

        }




        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

I think the problem is in your services hope this will help you, 我认为问题出在您的服务中,希望这对您有帮助,

      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; 
        }

       }

Call it anywhere you like 随便叫什么

       var _custList = new GetCustomers();

       var returnJson = await _custList.GetCustomers(); 

Note the return is json string format or xml format depending on your REST API so you need to parse this first before you can get the value and display it to ListView 请注意,返回值是json字符串格式还是xml格式,具体取决于您的REST API,因此您需要先进行解析,然后才能获取该值并将其显示到ListView

Try running it in UWP. 尝试在UWP中运行它。 If it works in UWP then you have to take a look at Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid 如果它可以在UWP中使用,则必须查看Xamarin HttpClient.GetStringAsync在Xamarin.Droid上不起作用

I had the same issue but when I tried it in UWP it worked fine. 我有同样的问题,但是当我在UWP中尝试时,它工作正常。 I am still seeking for the solution to run xamarin.android using device. 我仍在寻找使用设备运行xamarin.android的解决方案。

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

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