Hopefully this will save someone else a headache or two or three when it comes to getting a .NET Core API to play nice with an Android Emulator.
- Windows 10
- Visual Studio 2017
- .NET Core API is using IIS Express
- Swagger Installed
- Android Emulator/Android Device connected to computer
Android Emulator Setup
Each instance of the Android emulator operates behind a virtual router/firewall service. The virtual router/firewall isolates the Android emulator from your development machine network interfaces and settings and from the Internet. The Android emulator cannot see your development machine or other Android emulator instances running on the network. Instead, the Android emulator sees only that it is connected through Ethernet to a router/firewall.
The main take-away is that the IP Address 10.0.2.2 is a special alias to your host loop-back interface (i.e., 127.0.0.1 on your development machine). To access your development machine you will use the 10.0.2.2 IP Address from the browser running on the Android emulator.
See Set up Android Emulator networking for more information.
.NET Core API Setup
By default, APIs using IISExpress are only accessible via localhost, e.g. http://localhost:<PORT_NUMBER>. If you want to use a different IP Address, such as 127.0.0.1, you will need to update the applicationhost.config file.
The applicationhost.config file can be found in the .vs folder of your .NET Core API project.
You may have to close out of Visual Studio and reopen it, either way, need to make sure you are running Visual Studio as an Administrator.
Then when you fire up your .NET Core API, you will see that IIS Express is running it on two IP Addresses.
Now in our Android Emulator we can navigate to http://10.0.2.2:61459/swagger and will see the Swagger documentation, instead of the Bad Request – Invalid Hostname error.
What if you need access the API from front-end client, such as a React application?
You just need to add or modify the .env.development.local environment file and where it points to localhost for an API endpoint, change it to 10.0.2.2 instead.
What if you are using a Back-end for Front-end architecture approach?
You will still need your front-end client application to point to 10.0.2.2 for any front-end APIs it would need to access, but as for the back-end APIs, the front-end API can continue using localhost.