我有一个我创建的 Web API,只要对象 Content-Type 是 application/json
就可以发布 JSON 对象。我们想使用来自移动设备的 protobuf 将数据发送到 web api。如果我将 Content-type 切换为 x-protobuf
并且尽管将此格式化程序添加到我的 WebApiConfig
config.Formatters.Add(new ProtoBufFormatter());
当我使用 Chrome 扩展程序“Advanced Rest Client”或 Fiddler 时,看起来 Web Api 会在我执行 Get 时发送序列化响应,但当设置为 protobuf 时我没有看到它接收到发布请求。
到目前为止,Controller 类的测试方法 header 如下所示:
[HttpPost]
public override async Task<LoginResponse> Post([FromBody]LoginRequest request)
{...}
我还需要做什么来确保我的 WebApi 将反序列化 protobuf 序列化的请求。
您需要什么帮助?请并感谢您的考虑。
最佳答案
客户端必须使用 protobuf 序列化发送请求。 Advanced Rest Client(或 Fiddler)不序列化对象。我编写了一个测试工具客户端,将对象序列化为
byte[] rawBytes = ProtoBufSerializer.ProtoSerialize<LoginRequest>(loginRequest);
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
var byteArrayContent = new ByteArrayContent(rawBytes);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");
var result = client.PostAsync("Api/Login", byteArrayContent).Result;
关于c# - 通过 Web Api 中的请求支持 Protobuf-net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45715727/