无网络时代码退出,无法捕获异常

Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 32,386 信誉分 Microsoft 供应商
2024-08-23T08:41:50.87+00:00

你好

此代码在在有网络时完美运行,当离线未连接到互联网时,我想分配静态引脚,但此代码正在退出并且没有使用 list1 加载问题。

异常:

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); }

    }

}

提前致谢

此问题整理于:https://learn.microsoft.com/en-us/answers/questions/1883475/code-exiting-when-offline-not-able-to-capture-exce

.NET MAUI
.NET MAUI
一种 Microsoft 开源框架,用于构建跨移动设备、平板电脑、台式机的原生设备应用程序。
89 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 44,011 信誉分 Microsoft 供应商
    2024-08-23T08:52:55.4133333+00:00

    你好,

    对于这个问题,可以使用 Maui 提供的 Connectivity 接口,在调用 HTTP 接口之前,先做一次连接判断。

    请参考以下代码和文档:

    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");
        }
    }
    

    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。 注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。