.NET 7 MAUI集成Google Drive API报错:平台不支持启动授权浏览器
解决MAUI .NET7对接Google Drive的授权错误问题
你遇到的System.NotSupportedException是因为GoogleWebAuthorizationBroker是为桌面应用设计的授权组件,MAUI(尤其是Android平台)不支持它自动启动浏览器的逻辑,需要改用适配移动平台的OAuth2授权方案。以下是实现文件上传到Google Drive的完整步骤:
1. 替换授权依赖库
安装适配MAUI的Google授权NuGet包,同时保留Drive API的核心库:
Google.Apis.Auth.Maui(MAUI专属授权组件)Google.Apis.Drive.v3(Drive API操作库)
2. 修改授权代码,使用MAUI专属授权逻辑
替换原有的CreateAsync方法,用GoogleAuth.AuthorizeAsync替代桌面端的授权逻辑:
using Google.Apis.Auth.Maui; using Google.Apis.Drive.v3; using Google.Apis.Services; public static async Task<DriveService> CreateDriveServiceAsync() { try { // 仅请求Drive文件操作权限,符合上传需求 string[] scopes = { DriveService.Scope.DriveFile }; // 从Google Console获取的Android Client ID(client_secret.json中Android类型的client_id) var clientSecrets = new ClientSecrets { ClientId = "你的Android Client ID", // Android客户端无需Client Secret,留空即可 ClientSecret = string.Empty }; // 使用MAUI授权组件完成OAuth2流程 var credential = await GoogleAuth.AuthorizeAsync( clientSecrets, scopes, "user", CancellationToken.None); // 初始化Drive服务 return new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Greeks WT", }); } catch (Exception e) { Console.WriteLine($"授权失败:{e.Message}"); throw; } }
3. 配置Android平台的权限与回调
3.1 添加网络权限
在Platforms/Android/AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
3.2 配置OAuth回调Intent Filter
授权完成后Google需要跳回你的应用,在AndroidManifest.xml的<activity>标签内添加Intent Filter,scheme要和Google Console中配置的Redirect URI一致:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 格式:com.googleusercontent.apps.{你的Client ID前缀}:/oauth2redirect --> <data android:scheme="com.googleusercontent.apps.xxxxxxxxx" /> </intent-filter>
注:Google Console中Android客户端的Redirect URI默认格式为
com.googleusercontent.apps.{client-id}:/oauth2redirect,需确保此处scheme与之一致。
4. 实现文件上传功能
获取到DriveService后,即可调用Drive API完成文件上传:
public static async Task UploadFileToDriveAsync(DriveService driveService, string localFilePath, string driveFileName) { // 配置上传文件的元数据 var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = driveFileName, Parents = new List<string> { "root" } // 上传至Drive根目录,可替换为目标文件夹ID }; // 读取本地文件流并上传 using var fileStream = new FileStream(localFilePath, FileMode.Open); var uploadRequest = driveService.Files.Create(fileMetadata, fileStream, "application/octet-stream"); uploadRequest.Fields = "id"; // 指定返回字段,仅获取文件ID await uploadRequest.UploadAsync(); var uploadedFile = uploadRequest.ResponseBody; Console.WriteLine($"文件上传完成,ID:{uploadedFile.Id}"); }
关键注意事项
- 确保Google Console中创建的是Android类型的OAuth Client ID,并正确配置了应用的包名和SHA-1指纹(发布版需配置)。
- 测试时需使用真实设备或带Google Play服务的模拟器,否则可能无法正常完成授权流程。
内容的提问来源于stack exchange,提问作者Walter Torricos
相关产品推荐
相关产品推荐

