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

.NET MAUI安卓应用连接Google Sheets API遇平台不支持问题求助

在MAUI应用中连接Google Sheets API并更新电子表格的正确方法

你当前使用的GoogleWebAuthorizationBroker是为桌面应用设计的授权组件,它依赖环回IP处理授权回调,而移动端(安卓)不支持这种机制,因此抛出"platform not supported"异常。以下是适配MAUI移动端的正确实现方案:

一、调整Google控制台配置

  • 确认安卓凭证的包名和SHA-1指纹与你的MAUI安卓项目完全匹配
  • 记录凭证对应的回调URL,格式为 com.googleusercontent.apps.【你的Client ID前缀】://oauth2redirect(例如com.googleusercontent.apps.1234567890-abcdefghijklmnop://oauth2redirect)

二、配置MAUI安卓项目

在安卓项目的AndroidManifest.xml中添加以下Intent Filter,用于捕获授权回调:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <!-- 替换为你的回调URL的scheme部分 -->
    <data android:scheme="com.googleusercontent.apps.【你的Client ID前缀】" />
</intent-filter>

三、替换授权逻辑(核心修改)

放弃GoogleWebAuthorizationBroker,改用适配移动端的授权码流实现:

1. 安装必要NuGet包

确保已安装Google.Apis.Sheets.v4和Google.Apis.Auth这两个包。

2. 实现授权与服务初始化

using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Maui.ApplicationModel;

public class SheetsApiService
{
    private static readonly string[] _scopes = { SheetsService.Scope.Spreadsheets };
    private const string _appName = "你的应用名称";
    private const string _clientId = "你的安卓Client ID";
    // 替换为你的回调URL
    private const string _redirectUri = "com.googleusercontent.apps.【你的Client ID前缀】://oauth2redirect";

    private string _authCode;

    public async Task<SheetsService> GetAuthorizedServiceAsync()
    {
        UserCredential credential;
        var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets { ClientId = _clientId },
            Scopes = _scopes,
            DataStore = new FileDataStore("MauiSheetsAuth", true)
        });

        // 检查是否有已保存的有效令牌
        var storedToken = await flow.DataStore.GetAsync<TokenResponse>("user");
        if (storedToken != null && !storedToken.IsExpired(flow.Clock))
        {
            credential = new UserCredential(flow, "user", storedToken);
        }
        else
        {
            // 打开浏览器发起授权请求
            var authUrl = flow.CreateAuthorizationCodeRequest(_redirectUri).Build();
            await Launcher.OpenAsync(authUrl);

            // 等待回调获取授权码(通过DeepLink机制)
            while (string.IsNullOrEmpty(_authCode))
            {
                await Task.Delay(500);
            }

            // 用授权码交换访问令牌
            var newToken = await flow.ExchangeCodeForTokenAsync("user", _authCode, _redirectUri, default);
            await flow.DataStore.StoreAsync("user", newToken);
            credential = new UserCredential(flow, "user", newToken);
        }

        // 返回初始化后的Sheets服务
        return new SheetsService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = _appName
        });
    }

    // 处理DeepLink回调,获取授权码
    public void HandleAuthCallback(Uri callbackUri)
    {
        var queryParams = HttpUtility.ParseQueryString(callbackUri.Query);
        _authCode = queryParams.Get("code");
    }
}

3. 配置DeepLink回调处理

在App.xaml.cs中重写OnAppLinkRequestReceived方法,接收授权回调:

protected override void OnAppLinkRequestReceived(Uri uri)
{
    base.OnAppLinkRequestReceived(uri);
    // 建议使用依赖注入管理SheetsApiService实例,此处为示例简化
    var sheetsService = new SheetsApiService();
    sheetsService.HandleAuthCallback(uri);
}

四、更新电子表格示例

获取授权后的SheetsService后,即可执行更新操作:

var sheetsService = await new SheetsApiService().GetAuthorizedServiceAsync();
var spreadsheetId = "你的电子表格ID";
var targetRange = "Sheet1!A1"; // 要更新的单元格范围

// 构造要更新的数据
var valueRange = new ValueRange
{
    Values = new List<IList<object>> { new List<object> { "MAUI应用更新的内容" } }
};

// 发起更新请求
var updateRequest = sheetsService.Spreadsheets.Values.Update(valueRange, spreadsheetId, targetRange);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
var response = await updateRequest.ExecuteAsync();

// 验证更新结果
if (response.UpdatedCells > 0)
{
    // 更新成功逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:28:10