Well it resolved when I restarted Visual Studio. Weird!
HTTPClient fails on metered connection and working fine on wifi [closed]
-
08-10-2022 - |
Question
My app works fine with WiFi but when it is over 3G connection it crashes.
here is the code:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
await App.ViewModel.LoadDataAsync();
DataContext = App.ViewModel;
}
}
Code for LoadDataAsync
public async Task<bool> LoadDataAsync()
{
Uri uri = new Uri("http://www.28cinema.az/eng/");
HttpClient client = new HttpClient();
HtmlDocument htmlDocument = new HtmlDocument();
HtmlNode htmlNode = new HtmlNode(0, htmlDocument, 1);
MovieGroup data = new MovieGroup();
string HtmlResult;
HtmlResult = await client.GetStringAsync(uri);
data.Title = "Today";
htmlDocument.LoadHtml(HtmlResult);
htmlNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='poster_wrapper']");
for (var i = 0; i < (htmlNode.ChildNodes.Count); i++)
{
data.Items.Add(new MovieData
{
DetailsUrl = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/div[1]/div[1]/a[1]").GetAttributeValue("href", ""),
Title = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/div[1]/div[1]/a[1]").InnerText,
Poster = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/img").GetAttributeValue("src", "No poster"),
Cinema = "28 Cinema"
});
}
Today = data;
IsDataLoaded = true;
return true;
}
Exception message : No network connection and A task was canceled.
Stack Trace :
at Cineman.ViewModels.MovieModel.<CreateTodayGroupAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Cineman.ViewModels.MovieModel.<LoadDataAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Cineman.MainPage.<OnNavigatedTo>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
Any suggestions will be appreciated.
UPD: further looking revealed this line in local variables during breakpoint: 'htmlNode.InnerHtml' threw an exception of type 'System.NullReferenceException'
Solution 2
OTHER TIPS
As you discovered, if you attempt to do an HTTP request while there is no network connection, it will throw an exception.
I recommend that you handle the exception, e.g., with a try
/catch
. How you display the exception details to the user is up to you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow