Reputation: 63
I can't figure out why my await client.GetAsync is returning null when trying to get data from my web api controller. I hit the controller method successfully, but afterwards my mobile PCL method exits from my client.GetAsync line. Am I missing something? Here is my mobile method:
public async void onLoginClicked(object sender, EventArgs e)
{
var url = BaseUrl + "/loginapi/login?username=" + eUserName.Text + "&password=" + ePassword.Text;
var client = new HttpClient() { BaseAddress = new Uri(url) };
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var jsonResponse = string.Empty;
try
{
using (client)
{
var getDataResponse = await client.GetAsync("", HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
//If we do not get a successful status code, then return an empty set
if (!getDataResponse.IsSuccessStatusCode)
jsonResponse = null;
//Retrieve the JSON response
jsonResponse = await getDataResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (jsonResponse != null)
{
//map object
await Navigation.PushAsync(new CalendarView());
}
}
}
Upvotes: 0
Views: 4272
Reputation: 1
Try setting "Copy Local" property of the System.Net.Http reference of your PCL class to false, and adding the System.Net.Http reference to both your android and iOS project.
Apparently the System.Net.Http reference behaves unexpectedly in PCLs. There is more information on this thread.
https://forums.xamarin.com/discussion/7719/using-httpclient
Upvotes: 0
Reputation: 1123
You should not be using async void
(see the https://msdn.microsoft.com/en-us/magazine/jj991977.aspx article for a more thorough explanation - especially around the exception semantics).
My suggestion is to change your method signature to the following:
public async Task onLoginClicked(object sender, EventArgs e)
You will then be able to wrap your await statement in a try/catch to look for any exceptions been thrown.
Upvotes: 1