XAML in Xamarin.Forms 基礎篇 電子書

XAML in Xamarin.Forms 基礎篇 電子書
XAML in Xamarin.Forms 基礎篇 電子書

Xamarin.Forms 快速入門 電子書

Xamarin.Forms 快速入門 電子書
Xamarin.Forms 快速入門 電子書

2020/04/05

在開發 Xamarin.Forms 專案的時候,可以讓 Android Emulator 模擬器存取本機 localhost ASP.NET Core Web API 服務的做法

在開發 Xamarin.Forms 專案的時候,可以讓 Android Emulator 模擬器存取本機 localhost ASP.NET Core Web API 服務的做法

當在進行 Xamarin.Forms 專案開發設計的時候,由於後端系統尚在開發過程中,因此,將會需要在本機來啟動這個開發中的 Web API 服務。
例如,當使用 ASP.NET Core 來開發出一個 Web API 專案,此時,若要存取這個專案所提供的 Web API 服務,就需要使用類似這樣的 URI https://localhost:5001/weatherforecast ,不過,從這個 URL 將會發現到,這個主機使用了 localhost ,使用 Xamarin.Forms 所開發出來的 Android 專案,將會在 Android Emulator 模擬器下來運行,此時,在 Android 模擬器下,對於這個 localhost 主機,將只會存取到本身模擬器內的 5001 埠,可是,這台 Android 模擬器內的 5001 埠內,並沒有任何 Web API 服務,該服務存在取當時開發主機的作業環境下。
在這篇文章中,將會嘗試提出一個解法 (當然,對於這樣的問題,是有其他不同的解決方法,大家可以想看看還有哪些方法呢?)
在此,請先建立一個 ASP.NET Core 的 Web API 專案
請打開 Startup.cs 檔案,為了將整個展示過程予以簡化,因此,將不會強制使用 HTTPS 這樣的協定,所以,找到 app.UseHttpsRedirection(); 敘述,將其註解起來。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    //app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
接著,在命令提示字元視窗內,輸入 ipconfig 命令,將會出現如下內容,這在這裡可以找到當前這台電腦中所使用 ip address,這裡將會看到 ip = 192.168.31.153
.
.
.
無線區域網路介面卡 Wi-Fi:

   連線特定 DNS 尾碼 . . . . . . . . :
   連結-本機 IPv6 位址 . . . . . . . : fe80::b975:1a80:f870:eb77%16
   IPv4 位址 . . . . . . . . . . . . : 192.168.31.153
   子網路遮罩 . . . . . . . . . . . .: 255.255.255.0
   預設閘道 . . . . . . . . . . . . .: 192.168.31.1
.
.
.
在這個 ASP.NET Core Web API 專案內,展開 Properties 節點,將會看到 launchSettings.json 這個檔案,請打開這個檔案。
找到 CoreLocalAPI 這個屬性,從該屬性內找到 applicationUrl 這個節點,將該節點值修正為 https://localhost:5001;http://localhost:5000;https://192.168.31.153:5001;http://192.168.31.153:5000
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:63459",
      "sslPort": 44333
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CoreLocalAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000;https://192.168.31.153:5001;http://192.168.31.153:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
現在,可以使用命令提示字元視窗,切換到這個 API 專案所在的目錄下,並且輸入 dotnet run
如此,這個 Web API 專案便會在本機上開始執行了,從底下的啟動文字內容中,可以看到除了原先可以使用的 http://localhost:5000 URL 之外,還可以透過 http://192.168.31.153:5000 這個 URL 來連線到這 Web API 服務上。
Microsoft Windows [版本 10.0.18363.693]
(c) 2019 Microsoft Corporation. 著作權所有,並保留一切權利。

D:\Vulcan\Projects\CallLocakAPI\CoreLocalAPI>dotnet run
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://192.168.31.153:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://192.168.31.153:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\Vulcan\Projects\CallLocakAPI\CoreLocalAPI
因此,當在瀏覽器中輸入了 http://192.168.31.153:5000 URL 之後,將會看到底下的輸出內容
[{"date":"2020-03-10T12:21:44.4886014+08:00","temperatureC":-7,"temperatureF":20,"summary":"Mild"},{"date":"2020-03-11T12:21:44.4889745+08:00","temperatureC":44,"temperatureF":111,"summary":"Mild"},{"date":"2020-03-12T12:21:44.4889768+08:00","temperatureC":-19,"temperatureF":-2,"summary":"Hot"},{"date":"2020-03-13T12:21:44.488977+08:00","temperatureC":23,"temperatureF":73,"summary":"Scorching"},{"date":"2020-03-14T12:21:44.4889772+08:00","temperatureC":52,"temperatureF":125,"summary":"Balmy"}]
當確認 Web API 可以透過本機電腦的 WIFI IP 連線之後(不再僅需要透過 localhost 才能夠連線),現在可以來建立一個 Xamarin.Forms 的專案。
其中 View 的內容如下
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CallLocakAPI.Views.MainPage"
             Title="{Binding Title}">

    <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
        <Label Text="Welcome to Xamarin Forms and Prism!" />
        <Label Text="{Binding IP}" FontSize="16" TextColor="Blue"/>
        <Label Text="{Binding APIResult}" FontSize="14" TextColor="Red"/>
    </StackLayout>

</ContentPage>
而 ViewModel 的程式碼如下
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CallLocakAPI.ViewModels
{
    using System.ComponentModel;
    using System.Net.Http;
    using Localhost;
    using Prism.Events;
    using Prism.Navigation;
    using Prism.Services;
    using Xamarin.Essentials;

    public class MainPageViewModel : INotifyPropertyChanged, INavigationAware
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private readonly INavigationService navigationService;
        public string IP { get; set; }
        public string APIResult { get; set; }
        public MainPageViewModel(INavigationService navigationService)
        {
            this.navigationService = navigationService;

        }

        public void OnNavigatedFrom(INavigationParameters parameters)
        {
        }

        public async void OnNavigatedTo(INavigationParameters parameters)
        {
            IP = CrossLocalhost.Current.Ip;

            HttpClient client = new HttpClient();
            string result;
            try
            {
                APIResult = await client.GetStringAsync("http://192.168.31.153:5000/weatherforecast");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

        public void OnNavigatingTo(INavigationParameters parameters)
        {
        }

    }
}
這個測試結果將會如下圖,從底下截圖的執行結果中可以看到這個 Android 模擬器當時使用 IP Address 為 10.0.2.2,而可以實際連線到本機電腦上跑的 Web API,並且得到執行結果。



沒有留言:

張貼留言