'Asp.net core wed API on Xamarin Forms
This might be a not so wise question, but I am having hard times to understand the principles. I am working on Xamarin Forms project where I would like to use Azure SQL. I have watched several tutorials and understood that I need to create an Asp.net Core Web API for providing SQL operations. I have created such an API and tested it with Swagger on my computer. It is able to read and write into my Azure SQL database. I have my codes in Xamarin Forms for accessing this API service, but I am having hard times understanding how to proceed further?
Can I run this API somehow in Android directly? I mean can this API be part of my Xamarin Forms application and run inside Android or I have to upload this Asp.net Core Web API application into Azure and then access it with https link from my Xamarin Forms application? Should it be hosted on web or can it run directly inside Andoird like it runs on my Windows PC with access from localhost:7250/api/datarecord?
According to my understanding it can run on Android?
I have added this into my App.xaml.cs in Xamarin Forms:
public static string AzureBackendUrl =
DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5000" : "http://localhost:5000";
Then I have this Service in Xamarin Forms:
public class AzureDataStore : IRepository<DataRecord>
{
HttpClient client;
IEnumerable<DataRecord> items;
ILogger<AzureDataStore> logger;
public AzureDataStore(ILogger<AzureDataStore> logger = null, IHttpClientFactory httpClientFactory = null)
{
this.logger = logger;
client = httpClientFactory == null ? new HttpClient() : httpClientFactory.CreateClient("AzureWebsites");
if (httpClientFactory == null)
client.BaseAddress = new Uri($"{App.AzureBackendUrl}/");
items = new List<DataRecord>();
}
bool IsConnected => Connectivity.NetworkAccess == NetworkAccess.Internet;
public async Task<IEnumerable<DataRecord>> GetAll()
{
logger?.LogCritical("Getting items!!! Wow!");
if (IsConnected)
{
string json = await client.GetStringAsync($"api/DataRecord");
items = await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<DataRecord>>(json));
}
return items;
}
...
However once I am running this all together on my Android phone, my application is not able to communicate with WEB API for some reason.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
