c# - 通过 Web Api 中的请求支持 Protobuf-net

标签 c# asp.net-web-api protobuf-net

我有一个我创建的 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/

相关文章:

c# - 将通用列表转换为 ISet

C# @ 在枚举中从 XSD 生成的类

c# - 仅选择美国时区

http - CORS - ...不支持 http 方法 'OPTIONS'

c# - 无法将类型为 'Newtonsoft.Json.Linq.JObject' 的对象转换为类型 'Newtonsoft.Json.Linq.JArray'

c# - 如何绑定(bind)到 wpf 中另一个对象的属性?

具有 MVC4 内容的 jQuery 选项卡

c# - 我应该如何在 C# 中使用 WellKnownTypes?

protobuf-net - 没有为类型 : System. Drawing.Color 定义序列化程序

c# - Protobuf-net 无法仅使用 getter 序列化属性 - 无法将更改应用到属性