.netcore包中缺少ProtoBufFormatter

时间:2019-03-08 20:08:56

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

我正在尝试将此代码从.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 我该如何重写?

1 个答案:

答案 0 :(得分:1)

这是我在这里找到的另一种方法: 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;
}