ZZZ
ZZZ

Reputation: 2812

Xamarin app running in local emulator to talk to Web API hosted in local IIS?

My dev machine is sitting in local LAN, with a local static IP address. And the emulator is basically another device, so app should use the local static IP address rather than localhost or 127.0.0.1. So I have such hard coded base URI:

                var baseUri = new Uri("http://192.168.0.8:9030/webapi/");

It is not nice if the other developers need to test the code. I am thinking of putting the base uri in a config file, and before deploying the emulator, update the config file with the local IP address of the dev machine.

Is there built-in config file or build mechanism in Xamarin for such purpose? or how would you test with Web API with local IIS and local emulator?

I am using Visual Studio 2017 Professional.

Upvotes: 0

Views: 733

Answers (1)

SushiHangover
SushiHangover

Reputation: 74094

  1. The Android emulator has a virtual/dedicated private subnet that it uses and the IP of 10.0.2.2 is what the emulator maps the host system to (so 10.0.2.2 on the emulator is the host's localhost/127.0.0.1).

  2. You certainly can add a text file (json/xml/etc..) to the project and load/read an IP value from it at runtime.

    a. Assembly Embedded File: How to read embedded resource text file

    b. Instead of using an assembly embedded file, you can use the native platform application read-only bundle to store your config file and read it at runtime from your native app or .NetStd library. (Note: I prefer this method over assembly embedding.)

Xamarin.Essentials' OpenAppPackageFileAsync provides an easy way to access read-only bundled files in your application (AndroidAssets, BundleResource, etc..)

using (var stream = await FileSystem.OpenAppPackageFileAsync("sushiConfig.json"))
{
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
}

Upvotes: 2

Related Questions