c# - .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 我该如何重写它?
解决方案
这是我在这里找到的另一种方法: 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;
}
推荐阅读
- apache - Apache Proxypass 将代理端口与 HTTP 请求一起附加
- angular - 如何在 SeatMap anychart 中以编程方式选择座位?
- python - Matplotlib:带有变量的图例条目
- chart.js - Chart.js 将 x 轴标签向右移动
- android - 如何使用 recylerview 适配器中的共享首选项保存喜欢和不喜欢 imageview 按钮的状态,如 instagram
- vue.js - 在 Vue JS 中的组件内自动导入组件
- java - com.googlecode.javacv.FrameGrabber$Exception: cvCreateCameraCapture() 错误:无法创建相机捕捉
- docker - 关于为新容器应用 docker 命名卷的奇怪问题
- docker - 在 CircleCI 工作流或作业之后触发 Github Action
- python - 当我尝试添加反应 python 时出现 on_message 错误