February 25th, 2019

Quick Tip: Debugging Local ASP.NET Core Web APIs on Android Emulators

James Montemagno
Principal Manager, Tech PM

When developing mobile applications with a web API backend there is always a need to debug locally on your development machine. If you are using Visual Studio for Mac and debugging iOS applications you know it is as easy as running your web API locally and using localhost as the URL for web requests. However, this is not the case for Android debugging, because Android emulators have their own networking configuration whereas the iOS simulator uses the same network as the local machine. But we’ve got you, Android app developers, covered. With a little “know how” you can now also debug your Android apps locally regardless if you developing on Visual Studio on Windows or Visual Studio for Mac.

The first thing is to understand that Android has a special IP address to communicate and loop back to the host machine. The default Android emulators use 10.0.2.2 for this communication instead of localhost. Other emulators may use a different IP address, for instance, Genymotion uses 10.0.3.2. With this knowledge, you can configure your backend API to integrate with your mobile app. And since it’s usually common to place your web API calling code in shared code, you can use Xamarin.Essentials to determine what device the app is running on in order to pick the correct IP address.

Setup Xamarin.Essentials

To get started with Xamarin.Essentials you need to install the NuGet package. Use Xamarin.Essentials for your .NET Standard library if you are using one to share code across your iOS, Android, and UWP app projects.

After installing the NuGet, there is a small amount of code on Android that is required to initialize Xamarin.Essentials.

In the Android project’s `MainLauncher` or any `Activity` that is launched, Xamarin.Essentials must be initialized in the `OnCreate` method:

protected override void OnCreate(Bundle savedInstanceState) {
  //...
  base.OnCreate(savedInstanceState);
  Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
  //...

To handle runtime permissions on Android, Xamarin.Essentials must receive any OnRequestPermissionsResult. Add the following code to all Activity classes:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
  Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

  base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

Using Android Emulator Settings

Now that Xamarin.Essentials installed you can use the Device Information to check what platform the app is currently running on. Here is how you can transform the Xamarin.Forms project templates with an ASP.NET Core Web API to debug on Android:

public partial class App: Application
{
    public static string IPAddress = DeviceInfo.Platform == DevicePlatform.Android ? "10.0.2.2" : "localhost";
    public static string BackendUrl = $"http://{IPAddress}:5000";
}

After that, you can start making web requests with the newly optimized URL:

HttpClient client;

public AzureDataStore()
{
    client = new HttpClient();
    client.BaseAddress = new Uri($"{App.BackendUrl}/");
}

public ask<IEnumerable> GetItemsAsync(bool forceRefresh = false)
{
    var json = await client.GetStringAsync($"api/item");
    return Task.Run(() => JsonConvert.DeserializeObject<IEnumerable>(json));
}

Debugging on Windows

One important thing to remember on Windows is that you must use the default ASP.NET Core web server, i.e. Kestrel, to run the web API as IIS has additional isolation that will not work when communicating to this IP address.

You’ll also need to ensure that you don’t use the WebHost.CreateDefaultBuilder(args) option when bootstrapping your ASP.NET Core API as this will default to using IIS on windows. You can find out more about configuring Kestrel in the ASP.NET Core documentation. If you are debugging your application on Visual Studio for Mac it defaults to Kestrel so you have nothing to worry about.

Learn More

To learn more about Android networking in the emulator be sure to read through the full documentation from Google. Get started with ASP.NET Core to power your mobile applications and check out our awesome getting started guide on ASP.NET Core and Xamarin.

Author

James Montemagno
Principal Manager, Tech PM

James Montemagno is a Principal Lead Program Manager for Developer Community at Microsoft. He has been a .NET developer since 2005, working in a wide range of industries including game development, printer software, and web services. Prior to becoming a Principal Program Manager, James was a professional mobile developer and has now been crafting apps since 2011 with Xamarin. In his spare time, he is most likely cycling around Seattle or guzzling gallons of coffee at a local coffee shop. He ...

More about author

2 comments

Discussion is closed. Login to edit/delete existing comments.

  • Luis Quiles

    James,

    I’ve been searching online and watching youtube videos to no avail.
    I read your article and got the help I really needed on the first try!
    This is clean, simple and straight to the point.

    P.S: I signed up for all you videos on youtube, again, THANK YOU!