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

.NET WebAPI返回Protocol Buffer时报无效wire type错误如何解决?

问题根源

你遇到的这个报错本质原因是服务端返回的内容不是原始Protobuf二进制流:
.NET Framework 4.8 WebAPI的默认序列化逻辑中,直接调用Ok(byte[])返回字节数组时,会自动将字节数组做Base64编码后封装为JSON格式响应。客户端拿到的webMethodResponseAsByteArray本质是Base64字符串的UTF8编码结果,根本不是合法的Protobuf二进制数据,所以解析时会抛出无效wire type的异常。

修复方案

优先方案:修改服务端返回逻辑(推荐)

调整服务端Action的返回逻辑,跳过默认JSON序列化,直接返回原始Protobuf二进制流:

[HttpPost]
public async Task<IHttpActionResult> FetchSomeData()
{
    using (var ms = new MemoryStream(2048))
    {
        await content.CopyToAsync(ms).ConfigureAwait(false);
        byte[] bytes = ms.ToArray();
        MyRequest request = MyRequest.Parser.ParseFrom(bytes);

        MyResponse response = await SomeMethodAsync(request).ConfigureAwait(false);
        byte[] responseByteArray = response.ToByteArray();
        
        // 替换原有Ok返回逻辑,直接返回原始二进制
        var respMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(responseByteArray)
        };
        respMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        return ResponseMessage(respMessage);
    }
}

可选补充优化

  • 客户端发送请求时也指定Content-Type,避免服务端请求处理逻辑误修改请求体:
ByteArrayContent byteContent = new(byteArray);
// 新增行
byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
  • 确保服务端和客户端引用的公共Protobuf类库是同一版本,避免因proto定义不一致、字段编号不匹配导致的解析错误。

临时兼容方案(不推荐)

如果暂时无法修改服务端代码,可以在客户端对返回结果做Base64解码后再解析:

byte[] webMethodResponseAsByteArray = await content.ReadAsByteArrayAsync().ConfigureAwait(false);
// 先把字节数组转成UTF8字符串,再做Base64解码
string base64Str = Encoding.UTF8.GetString(webMethodResponseAsByteArray);
byte[] protoBytes = Convert.FromBase64String(base64Str.Trim('"')); // 注意去掉JSON字符串的前后引号
MyResponse webMethodResponse = MyResponse.Parser.ParseFrom(protoBytes);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:57:03