Code Exiting when Offline not able to capture exception

Kalyan A 440 Reputation points
2024-08-18T18:47:53.8866667+00:00

This code works perfectly in online, when offline not connected to internet , I want to assign static pins but this code is exiting and not loading Questions with list1.

Exception thriow

Exception thrown: 'System.Net.Sockets.SocketException' in System.Private.CoreLib.dll

Exception thrown: 'System.Net.Http.HttpRequestException' in System.Private.CoreLib.dll

The program '[6584] MauiAppMCQs.exe' has exited with code 0 (0x0).

@inject NavigationManager Navigation
@using System.Text;
@using System.Net.Http.Headers;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
 @using Microsoft.JSInterop;
@page "/Login"
<h3>Login</h3>
<EditForm Model="@submitActivity" OnSubmit="@Submit">
    <br />
    <div class="row">
        <div class="col-md-3">
            <p>PIN</p>
        </div>
        <div class="col-md-4">
            <input placeholder="PIN" @bind="@pin" />
        </div>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
    <div>
        @errmsg
    </div>
</EditForm>
@code {
    private int pin; private string jwttoken; private string connected; private string jsonString;
    public string @errmsg="";
    private ACTIVITY submitActivity { get; set; } = new();
    List<Questionpin> Questions = new List<Questionpin>();
    List<Questionpin> res;
      List<Questionpin> list1 = new List<Questionpin>()
        {
            new Questionpin(){Id = 1, Pinnum = 20120605 },
            new Questionpin(){Id = 2, Pinnum= 20240815}
        };
    public class Questionpin
    {
        public long Id { get; set; }
        public int  Pinnum { get; set; }
    }
    public class ACTIVITY
    {
        public string Dummy { get; set; }
    }
    private async void Submit()
    {
        var jsonContent = new StringContent(JsonConvert.SerializeObject(new
        {
            bodyField1 = ""
        }), Encoding.UTF8, "application/json");
         connected = "N";
        using (var client1 = new HttpClient())
        {
            string authurl = "https://myquizapi.azurewebsites.net/api/";
            client1.BaseAddress = new Uri(authurl);
            client1.DefaultRequestHeaders.Clear();
            client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage Res = await client1.PostAsync("Auth", jsonContent);
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api
                string json = await Res.Content.ReadAsStringAsync();
                // Parse the JSON response to extract the address
                dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                jwttoken = data1.token;
            }
        }
        string apiUrl = "https://myquizapi.azurewebsites.net/api/";
try
{ 
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(apiUrl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwttoken}");
            HttpResponseMessage response = null;
            response = await client.GetAsync("pins");
            // Check if the request was successful (status code 200)
            if (response.IsSuccessStatusCode)
            {
                // Make a GET request to the API
                connected = "Y";
                // Read the content of the response
                string jsonString = await response.Content.ReadAsStringAsync();
                // Deserialize the JSON string into an object
                Questions = JsonConvert.DeserializeObject<List<Questionpin>>(jsonString);
            }
            else{ Questions = list1;}
        }
}
catch(Exception ex)
{ if (connected == "N")
                {
                    Questions = list1;
                }}
        var result = Questions.FirstOrDefault(c => c.Pinnum == pin);
        if (result == null)
        {
            errmsg = "Enter Valid  pin";
        }
        else
        { Navigation.NavigateTo("/NewNav", true); }
    }
 
}
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
4,026 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 49,611 Reputation points Microsoft External Staff
    2024-08-19T02:38:03.2066667+00:00

    Hello,

    For this problem, you can use the Connectivity interface provided by Maui to make a connection judgment before calling the HTTP interface.

    Please refer to the following code and documentation:

    private async void Submit()
    {
        if(Connectivity.Current.NetworkAccess == NetworkAccess.Internet) // If the network is Internet state, then proceed with the following code
        {
            var jsonContent = new StringContent(JsonConvert.SerializeObject(new
            {
                bodyField1 = ""
            }), Encoding.UTF8, "application/json");
            connected = "N";
            using (var client1 = new HttpClient())
            {
                string authurl = "https://myquizapi.azurewebsites.net/api/";
                client1.BaseAddress = new Uri(authurl);
                client1.DefaultRequestHeaders.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage Res = await client1.PostAsync("Auth", jsonContent);
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    string json = await Res.Content.ReadAsStringAsync();
                    // Parse the JSON response to extract the address
                    dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    jwttoken = data1.token;
                }
            }
            string apiUrl = "https://myquizapi.azurewebsites.net/api/";
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwttoken}");
                    HttpResponseMessage response = null;
                    response = await client.GetAsync("pins");
                    // Check if the request was successful (status code 200)
                    if (response.IsSuccessStatusCode)
                    {
                        // Make a GET request to the API
                        connected = "Y";
                        // Read the content of the response
                        string jsonString = await response.Content.ReadAsStringAsync();
                        // Deserialize the JSON string into an object
                        Questions = JsonConvert.DeserializeObject<List<Questionpin>>(jsonString);
                    }
                    else { Questions = list1; }
                }
            }
            catch (Exception ex)
            {
                if (connected == "N")
                {
                    Questions = list1;
                }
            }
            var result = Questions.FirstOrDefault(c => c.Pinnum == pin);
            if (result == null)
            {
                errmsg = "Enter Valid  pin";
            }
            else
            { Navigation.NavigateTo("/NewNav", true); }
        }
        else
        {
            Console.WriteLine("No Internet");
        }
     
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.