You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI 6 WebView超时处理:指定网站连通性校验需求

MAUI 6 WebView 指定网站连通性校验与超时处理

一、校验指定网站的连通性

CrossConnectivity仅能检测设备是否联网,无法验证特定网站的可达性。可以通过HttpClient发送轻量的HEAD请求来实现:

using System.Net.Http;
using System.Threading.Tasks;

// 复用HttpClient实例提升性能
private static readonly HttpClient _httpClient = new HttpClient();

/// <summary>
/// 检测指定网站是否可达
/// </summary>
/// <param name="url">目标网站地址</param>
/// <param name="timeoutMilliseconds">超时时间(默认5000ms)</param>
/// <returns>是否可达</returns>
public async Task<bool> IsWebsiteReachable(string url, int timeoutMilliseconds = 5000)
{
    try
    {
        _httpClient.Timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
        // 发送HEAD请求,避免下载完整页面内容
        var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
        return response.IsSuccessStatusCode;
    }
    catch (HttpRequestException)
    {
        return false;
    }
    catch (TaskCanceledException)
    {
        // 请求超时
        return false;
    }
}

调用示例:

string targetUrl = "xxxxxxxxx.xxxxxx";
if (!await IsWebsiteReachable(targetUrl))
{
    await Application.Current.MainPage.DisplayAlert("提示", "目标网站无法访问,请检查网络", "确定");
    return;
}
webview.Source = targetUrl;

二、WebView导航过程中的超时监控

即使初始检测网站可达,导航过程中仍可能出现超时。可以通过WebView的导航事件结合任务超时来实现监控:

1. 绑定WebView导航事件

// 在初始化WebView时绑定事件
webview.Navigating += WebView_Navigating;
webview.Navigated += WebView_Navigated;
webview.NavigationFailed += WebView_NavigationFailed;

2. 实现超时监控逻辑

private CancellationTokenSource _navigationCts;

private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
    // 启动导航时创建取消令牌
    _navigationCts = new CancellationTokenSource();
    // 启动超时监控任务(设置为10秒超时)
    _ = MonitorNavigationTimeout(_navigationCts.Token, e.Url);
}

private void WebView_Navigated(object sender, WebNavigatedEventArgs e)
{
    // 导航完成,取消超时监控
    _navigationCts?.Cancel();
    _navigationCts?.Dispose();
}

private void WebView_NavigationFailed(object sender, WebNavigationFailedEventArgs e)
{
    // 导航失败,取消超时监控并提示用户
    _navigationCts?.Cancel();
    _navigationCts?.Dispose();
    MainThread.BeginInvokeOnMainThread(async () =>
    {
        await Application.Current.MainPage.DisplayAlert("加载失败", $"无法加载页面:{e.Message}", "确定");
    });
}

private async Task MonitorNavigationTimeout(CancellationToken token, string url)
{
    try
    {
        // 等待超时时间
        await Task.Delay(10000, token);
        // 触发超时提示
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await Application.Current.MainPage.DisplayAlert("提示", $"加载{url}超时,请检查网络后重试", "确定");
            // 停止WebView加载
            webview.StopLoading();
        });
    }
    catch (TaskCanceledException)
    {
        // 导航已完成,无需处理
    }
}

三、Android平台额外配置

结合你已有的WebViewHandler配置,可以添加自定义WebViewClient来处理Android平台的加载错误:

Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("Custom", (handler, view) =>
{
#if ANDROID
    handler.PlatformView.Settings.CacheMode = Android.Webkit.CacheModes.Default;
    handler.PlatformView.Settings.SetAppCacheEnabled(true);
    handler.PlatformView.Settings.JavaScriptEnabled = true;
    handler.PlatformView.AddJavascriptInterface(new JavaScriptHandler(), "Native");
    // 设置自定义WebViewClient处理加载错误
    handler.PlatformView.SetWebViewClient(new CustomWebViewClient());
#endif
});

// Android平台自定义WebViewClient
#if ANDROID
public class CustomWebViewClient : Android.Webkit.WebViewClient
{
    public override void OnReceivedError(Android.Webkit.WebView view, IWebResourceRequest request, WebResourceError error)
    {
        base.OnReceivedError(view, request, error);
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await Application.Current.MainPage.DisplayAlert("加载错误", error.DescriptionFormatted.ToString(), "确定");
        });
    }
}
#endif

内容的提问来源于stack exchange,提问作者graph User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:53:10