首页 > 解决方案 > .netcore 包中缺少 ProtoBufFormatter

问题描述

我正在尝试将此代码从 .net 4.5.2 转换为 .net 标准

string requestURIAction = ....;
MIObjectSetType objectSet = new ....;
CancellationToken cancelToken = new....;
this.Formatter = new ProtoBufFormatter();

HttpResponseMessage response = await client.PostAsync(requestURIAction, objectSet, this.Formatter, cancelToken);

我将 nuget 包 WebApiContrib.Formatting.Protobuf 替换为等效的 .net 标准版本 - WebAPiContrib.Core.Formatter.Protobuf

但是 WebAPiContrib.Core.Formatter.Protobuf 中不存在 ProtoBufFormatter 我该如何重写它?

标签: c#asp.net-core.net-standard

解决方案


这是我在这里找到的另一种方法: https ://damienbod.com/2017/06/30/using-protobuf-media-formatters-with-asp-net-core/

首先安装 WebApiContrib.Core.Formatter.Protobuf 2.0 nuget 包

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers().AddProtobufFormatters()
}

然后您可以使用以下代码而不是 ProtoBufFormatter 调用服务器并反序列化

static async System.Threading.Tasks.Task<Table[]> CallServerAsync()
{
    var client = new HttpClient();

    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:31004/api/tables");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
    var result = await client.SendAsync(request);
    var tables = ProtoBuf.Serializer.Deserialize<Table[]>(await result.Content.ReadAsStreamAsync());
    return tables;
}

推荐阅读