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

Xamarin应用连接Firebase Firestore出现Grpc.Core.RpcException错误求助

Xamarin连接Firestore报错:Grpc.Core.RpcException(HTTP/1.1降级)

我正在使用Xamarin开发应用,采用Firestore作为数据库,但在尝试连接并操作数据时遇到错误。

实现代码

// get google json file
string fileName = "private_key.json";
var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
using (var ms = new MemoryStream())
{
    stream.CopyTo(ms);
    byte[] payload = ms.ToArray();
    File.WriteAllBytes(Path.Combine(FileSystem.AppDataDirectory, fileName), payload);
}

var fileinfo = new FileInfo(Path.Combine(FileSystem.AppDataDirectory, fileName));
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", fileinfo.FullName);
Environment.SetEnvironmentVariable("GRPC_DNS_RESOLVER", "native");
              
// Enable HTTP / 2 support
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

// Create a FirestoreDb instance
FirestoreDb databaseFS = FirestoreDb.Create("appname");

// Get a reference to a collection
CollectionReference collectionRef = databaseFS.Collection("Collection_Name");

// Create a new document with an auto-generated ID
DocumentReference documentRef = await collectionRef.AddAsync(new { Name = "John", Age = 30 });

报错信息

Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Bad gRPC response. Response protocol downgraded to HTTP/1.1.")
  at Google.Api.Gax.Grpc.ApiCallRetryExtensions+<>c_DisplayClass0_0`2[TRequest,TResponse].<WithRetry>b0 (TRequest request, Google.Api.Gax.Grpc.CallSettings callSettings) [0x0016f] in //Google.Api.Gax.Grpc/ApiCallRetryExtensions.cs:39 
  at Google.Cloud.Firestore.WriteBatch.CommitAsync (Google.Protobuf.ByteString transactionId, System.Threading.CancellationToken cancellationToken) [0x00080] in /_/apis/Google.Cloud.Firestore/Google.Cloud.Firestore/WriteBatch.cs:226 
  at Google.Cloud.Firestore.DocumentReference.CreateAsync (System.Object documentData, System.Threading.CancellationToken cancellationToken) [0x00043] in /_/apis/Google.Cloud.Firestore/Google.Cloud.Firestore/DocumentReference.cs:106 
  at Google.Cloud.Firestore.CollectionReference.AddAsync (System.Object documentData, System.Threading.CancellationToken cancellationToken) [0x00044] in /_/apis/Google.Cloud.Firestore/Google.Cloud.Firestore/CollectionReference.cs:94 

请问出现该错误的原因是什么?该如何解决?Google.Firebase.Firestore应当与Xamarin兼容。


原因与解决方案

错误原因

这个错误的核心是gRPC请求被强制降级为HTTP/1.1,而Firestore的gRPC客户端需要HTTP/2协议才能正常工作。在Xamarin环境中,主要触发因素如下:

  1. 启用的Http2UnencryptedSupport仅针对未加密的HTTP连接,但Firestore使用HTTPS,该开关完全不生效。
  2. Xamarin默认HTTP Handler可能不支持HTTP/2,或gRPC客户端未正确绑定到支持HTTP/2的Handler。
  3. 移动端直接使用服务账号密钥(private_key.json)的方式不符合Firestore移动端使用规范,服务账号仅适用于后端服务场景。

解决方案

方案1:切换到Firebase官方移动端SDK(推荐)

Xamarin应用应使用针对移动端优化的Firebase Firestore SDK,而非后端的Google.Cloud.Firestore包,步骤如下:

  • 移除Google.Cloud.Firestore相关NuGet包,安装Xamarin.Firebase.Firestore包。
  • 在Firebase控制台下载对应平台的配置文件:Android为google-services.json,iOS为GoogleService-Info.plist,添加到项目后设置正确构建操作(Android设为GoogleServicesJson,iOS设为BundleResource)。
  • 初始化Firebase并操作Firestore:
// Android在MainActivity中初始化
FirebaseApp.InitializeApp(Application.Context);

// iOS在AppDelegate中初始化
FirebaseApp.Configure();

// 访问Firestore并添加数据
var db = FirebaseFirestore.Instance;
var collectionRef = db.Collection("Collection_Name");
var docData = new Dictionary<string, Java.Lang.Object>
{
    { "Name", "John" },
    { "Age", 30 }
};
await collectionRef.AddAsync(docData);

方案2:修复现有Google.Cloud.Firestore的HTTP/2支持(不推荐用于生产移动端)

如果必须使用后端SDK,需确保HTTP/2在Xamarin中正常工作:

  • 移除AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);,该开关对HTTPS连接无效。
  • 创建Firestore实例前,配置支持HTTP/2的gRPC Channel:
var credential = GoogleCredential.FromFile(fileinfo.FullName);
var channelOptions = new Grpc.Core.ChannelOptions
{
    HttpHandler = new System.Net.Http.SocketsHttpHandler
    {
        EnableMultipleHttp2Connections = true,
        AllowAutoRedirect = true
    }
};

var firestoreClient = new FirestoreClientBuilder
{
    ProjectId = "appname",
    Credential = credential,
    ChannelOptions = channelOptions
}.Build();

FirestoreDb databaseFS = FirestoreDb.Create("appname", firestoreClient);
  • 确保设备系统版本支持HTTP/2(Android 7.0+、iOS 9.0+),并将Xamarin相关NuGet包更新至最新稳定版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:52:39