我有“网络MAUI”应用程序,Im试图检查与我网站链接:
private void CheckAPIConnection(string url)
{
try
{
var request = WebRequest.CreateHttp(url);
request.Method = "GET";
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException ex2)
{
DisplayAlert("Error", $"An unexpected error occurred: {ex2.Message}", "OK");
}
catch (Exception ex3)
{
// Handle other exceptions
DisplayAlert("Error", $"An unexpected error occurred: {ex3.Message}", "OK");
}
if (response.StatusCode != HttpStatusCode.OK)
{
DisplayAlert("Error",
$"Connection failed. This may caused by your internet connection " +
$"or our API are currently overloading or temporarily unavailable.
" +
$"Please check your internet connection, and if your internet connection " +
$"don t have any problems, you may need to wait for an hour and then try again " +
$"due to our API are currently overloading or temporarily unavailable.
" +
$"Status code: {response.StatusCode}
Headers: {response.Headers}
" +
$"Content Type: {response.ContentType}
Content Length: {response.ContentLength}
" +
$"Last Modified: {response.LastModified}", "OK");
}
}
catch (System.Net.WebException ex2)
{
DisplayAlert("Error", $"An unexpected error occurred: {ex2.Message}", "OK");
}
catch (Exception ex)
{
// Handle other exceptions
DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
}
}
我用一个不知名的东道国来测试这一功能,以便检查所有工作:
CheckAPIConnection("https://lol.click/api/v1");
现在我有这个例外:
Exception has occurred: CLR/System.Net.WebException Exception thrown: System.Net.WebException in System.Net.Requests.dll: No such host is known. (lol.click:443) Inner exceptions found, see $exception in variables window for more details. Innermost exception System.Net.Sockets.SocketException : No such host is known. at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses, AddressFamily addressFamily, Nullable
1 startingTimestamp) at System.Net.Dns.GetHostAddresses(String hostNameOrAddress, AddressFamily family) at System.Net.Sockets.Socket.Connect(String host, Int32 port) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at System.Net.HttpWebRequest.<>c__DisplayClass219_0.<<CreateHttpClient>b__1>d.MoveNext() at System.Threading.Tasks.ValueTask
1.get_Result() at System.Net.Http.HttpConnectionPool.d__104.MoveNext()
我试图发布<>Continue,但我的方案在这一例外之后立即中断。 我的方案也在此例外之后立即终止。
这是例外情况的直观形象:
我无法抓住这一例外? 即便是Try-Schilling,这一例外也不可能被抓住,我感到很奇怪。
http://www.un.org。 我尝试了另一种做法,即使我试图赶上这一办法,这一例外仍然存在:
private async Task CheckAPIConnection(string url)
{
Thread.Sleep(10000);
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
{
if (!response.IsSuccessStatusCode)
{
await DisplayAlert("Error",
$"Connection failed. This may caused by your internet connection " +
$"or our API are currently overloading or temporarily unavailable.
" +
$"Please check your internet connection, and if your internet connection " +
$"don t have any problems, you may need to wait for an hour and then try again " +
$"due to our API are currently overloading or temporarily unavailable.
" +
$"Status code: {response.StatusCode}
Content: {response.Content}
" +
$"Headers: {response.Headers}
Trailings Headers: {response.TrailingHeaders}
" +
$"Reason Phrase: {response.ReasonPhrase}", "OK");
}
}
}
catch (Exception ex)
{
// Handle other exceptions
await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
}
}
例外:
using (HttpResponseMessage response = await client.GetAsync(url))
例外细节:
Exception has occurred: CLR/System.Net.Http.HttpRequestException Exception thrown: System.Net.Http.HttpRequestException in > System.Private.CoreLib.dll: No such host is known. (lol.click:443) Inner exceptions found, see $exception in variables window for more > details. Innermost exception System.Net.Sockets.SocketException : No such > host is known. at > System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(> SocketError error, CancellationToken cancellationToken) at > System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threadin> g.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) at System.Net.Sockets.Socket.> <g__WaitForConnectWithCancellation|285_0>d.MoveNext() at System.Net.Http.HttpConnectionPool.> d__104.MoveNext()
这里是所要求的全部法典:
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Controls;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace CyberCode;
public partial class SplashPage : ContentPage
{
public SplashPage()
{
InitializeComponent();
}
/// <summary>
/// Animation for application logo
/// </summary>
private async Task AnimationController()
{
imgSplashScreen.Opacity = 0;
Thread.Sleep(3 * 1000);
await imgSplashScreen.FadeTo(1, 1000);
}
private async Task CheckAPIConnection(string url)
{
Thread.Sleep(10000);
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
{
if (!response.IsSuccessStatusCode)
{
await DisplayAlert("Error",
$"Connection failed. This may caused by your internet connection " +
$"or our API are currently overloading or temporarily unavailable.
" +
$"Please check your internet connection, and if your internet connection " +
$"don t have any problems, you may need to wait for an hour and then try again " +
$"due to our API are currently overloading or temporarily unavailable.
" +
$"Status code: {response.StatusCode}
Content: {response.Content}
" +
$"Headers: {response.Headers}
Trailings Headers: {response.TrailingHeaders}
" +
$"Reason Phrase: {response.ReasonPhrase}", "OK");
}
}
}
catch (Exception ex)
{
// Handle other exceptions
await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
}
}
/// <summary>
/// Animation for ActivityIndicator
/// </summary>
private async Task AnimationActivityIndicator()
{
LoadingActivity.Opacity = 0;
Thread.Sleep(5 * 1000);
await LoadingActivity.FadeTo(1, 500);
await CheckAPIConnection("https://lol.click/api/v1");
}
private async Task AnimationExitActivityIndicator()
{
Thread.Sleep(20 * 1000);
await LoadingActivity.FadeTo(0, 1000);
}
private async Task ShowLogInElements()
{
Thread.Sleep(10 * 1000);
// Username
Frame entryFrameUsername = new Frame
{
BorderColor = Color.FromHex("#C49B33"),
CornerRadius = 10,
Padding = new Thickness(2, 8),
WidthRequest = 250,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Opacity = 0 // Set initial opacity to 0 for the appearing animation
};
Entry txtUsername = new Entry
{
MaxLength = 255,
BackgroundColor = Color.FromRgba(0, 0, 0, 0),
TextColor = Color.FromHex("#FFFFFF"),
PlaceholderColor = Color.FromHex("#a9a9a9"),
Placeholder = "Username"
};
entryFrameUsername.Content = txtUsername;
// Password
Frame entryFramePassword = new Frame
{
BorderColor = Color.FromHex("#FFFFFF"),
CornerRadius = 10,
Padding = new Thickness(2, 0),
WidthRequest = 255,
HorizontalOptions = LayoutOptions.Center,
Opacity = 0
};
}
protected override void OnAppearing()
{
base.OnAppearing();
Task.Run(async () => await AnimationController());
LoadingActivity.IsRunning = true;
Task.Run(async () => await AnimationActivityIndicator());
Task.Delay(TimeSpan.FromSeconds(10));
Task.Run(async () => await AnimationExitActivityIndicator());
}
}