C# .NET MAUI中WebView下载功能失效问题求助
解决.NET MAUI WebView中下载按钮无响应的问题
你的问题根源在于.NET MAUI的WebView默认不会自动处理网页中的下载请求,需要针对Android和iOS平台分别添加下载逻辑处理。以下是具体的实现步骤:
1. 为WebView添加平台特定的下载处理
Android平台
在Android项目中创建自定义WebView Handler,通过设置DownloadListener拦截下载请求:
using Android.Webkit; using Microsoft.Maui.Handlers; namespace YourAppName.Platforms.Android; public class CustomWebViewHandler : WebViewHandler { protected override void ConnectHandler(Android.Webkit.WebView platformView) { base.ConnectHandler(platformView); platformView.SetDownloadListener(new CustomDownloadListener()); } } public class CustomDownloadListener : Java.Lang.Object, IDownloadListener { public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength) { var request = new Android.App.DownloadManager.Request(Android.Net.Uri.Parse(url)); request.SetMimeType(mimetype); // 自动解析文件名 var filename = Android.Webkit.URLUtil.GuessFileName(url, contentDisposition, mimetype); request.SetTitle(filename); request.SetDescription("正在下载文件..."); request.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted); // 设置保存到系统下载目录 var destinationUri = Android.Net.Uri.WithAppendedPath( Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads), filename); request.SetDestinationUri(destinationUri); // 启动下载 var downloadManager = (Android.App.DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService); downloadManager.Enqueue(request); } }
在MauiProgram.cs中注册这个Handler:
builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler<Microsoft.Maui.Controls.WebView, YourAppName.Platforms.Android.CustomWebViewHandler>(); #endif });
iOS平台
在iOS项目中自定义WebView Handler,通过WKNavigationDelegate处理下载请求:
using WebKit; using Microsoft.Maui.Handlers; namespace YourAppName.Platforms.iOS; public class CustomWebViewHandler : WebViewHandler { protected override void ConnectHandler(WKWebView platformView) { base.ConnectHandler(platformView); platformView.NavigationDelegate = new CustomWKNavigationDelegate(); } } public class CustomWKNavigationDelegate : WKNavigationDelegate { public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler) { var request = navigationAction.Request; if (request.Url != null && IsDownloadRequest(request)) { webView.Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookies((cookies) => { var downloadTask = webView.StartDownload(request); downloadTask.Delegate = new CustomWKDownloadDelegate(); }); decisionHandler(WKNavigationActionPolicy.Cancel); return; } decisionHandler(WKNavigationActionPolicy.Allow); } // 简单判断是否为下载请求,可根据实际场景调整 private bool IsDownloadRequest(NSUrlRequest request) { var urlString = request.Url.AbsoluteString; var downloadExtensions = new[] { ".pdf", ".zip", ".docx", ".xlsx" }; return downloadExtensions.Any(ext => urlString.EndsWith(ext, StringComparison.OrdinalIgnoreCase)); } } public class CustomWKDownloadDelegate : WKDownloadDelegate { public override void DidFinishDownload(WKDownload download, NSUrl location) { // 将文件移动到Documents目录,方便用户访问 var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var destinationPath = Path.Combine(documentsPath, Path.GetFileName(location.AbsoluteString)); if (File.Exists(destinationPath)) File.Delete(destinationPath); File.Move(location.Path, destinationPath); // 提示用户下载完成 var alert = UIKit.UIAlertController.Create("下载完成", $"文件已保存到: {destinationPath}", UIKit.UIAlertControllerStyle.Alert); alert.AddAction(UIKit.UIAlertAction.Create("确定", UIKit.UIAlertActionStyle.Default, null)); UIKit.UIApplication.SharedApplication.KeyWindow?.RootViewController.PresentViewController(alert, true, null); } }
同样在MauiProgram.cs中注册iOS的Handler:
builder.ConfigureMauiHandlers(handlers => { #if IOS handlers.AddHandler<Microsoft.Maui.Controls.WebView, YourAppName.Platforms.iOS.CustomWebViewHandler>(); #endif });
2. 额外配置与注意事项
Android权限:在
AndroidManifest.xml中添加必要权限:<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />Android 13及以上需补充媒体访问权限,可根据需求添加
android.permission.READ_MEDIA_IMAGES等。iOS文件共享:若要让用户在系统文件应用中看到下载文件,需在
Info.plist中添加:<key>UIFileSharingEnabled</key> <true/> <key>LSSupportsOpeningDocumentsInPlace</key> <true/>动态WebView验证:确保
webViewerS创建后能自动关联自定义Handler(全局注册后动态创建的WebView会自动生效),可先用公开下载链接(如https://sample-videos.com/pdf/Sample-pdf-5mb.pdf)测试功能是否正常。
内容的提问来源于stack exchange,提问作者Manuel Galleani
相关产品推荐
相关产品推荐

