使用POSTMAN发送一个包含Protobuf数据的请求

huangapple go评论62阅读模式
英文:

Posting a request from POSTMAN with protobuf in the body

问题

以下是您提供的信息的翻译:

我想要在Postman中以Protobuf消息的形式发送POST请求,并在我的服务方法中设置断点,同时将Protobuf消息反序列化为C#对象,但这并没有发生。在Postman中,我得到了以下错误。

415 不支持的媒体类型

GET请求可以正确运行并命中服务中的断点,然后返回Protobuf格式的数据,但POST请求甚至不会触发断点。我尝试将返回的Protobuf格式数据添加到POST请求的请求体中来进行测试,但这也没有成功。

以下是GET和POST的服务代码。

[ApiController]
public class ItemController : ControllerBase
{
    [HttpGet]
    [Produces("application/x-protobuf")]
    public IActionResult Get()
    {
        List<Item> items = new List<Item>
        {
            new Item { Id = 1, Name = "Item 1", Value = 4 },
            new Item { Id = 2, Name = "Item 2", Value = 3 }
        };
        return Ok(items);
    }

    [HttpPost]
    [Consumes("application/x-protobuf", "application/json")]
    [Produces("application/x-protobuf")]
    public IActionResult Post([FromBody] Item myItem)
    {
        List<Item> items = new List<Item>
        {
            new Item { Id = 1, Name = "Item 5", Value = 4 },
            new Item { Id = 2, Name = "Item 7", Value = 3 }
        };

        items.Add(myItem);
        return Ok(items);
    }
}

模型如下:

using ProtoBuf;

namespace ProtobufService
{
    [ProtoContract]
    public class Item
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
        [ProtoMember(3)]
        public long Value { get; set; }
    }
}

服务项目中的库如下...

[插入图片链接]

[插入图片链接]

[插入图片链接]

[插入图片链接]

我编写了一个控制台应用程序作为测试客户端。这个客户端可以正确执行GET和POST请求,并且可以触发断点。以下是客户端的代码...

private static async Task GetProtobufData(HttpClient client)
{
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5163/api/item");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
    var result = await client.SendAsync(request);
    var tables = ProtoBuf.Serializer.Deserialize<Item[]>(await result.Content.ReadAsStreamAsync());

    string itemproto = Serializer.GetProto<Item>();
    Console.WriteLine(itemproto);

    Console.WriteLine("从GET返回的值是:" + tables[1].Name);
    Console.ReadLine();
}

private static async Task PostProtobufData(HttpClient client)
{
    MemoryStream stream = new MemoryStream();
    ProtoBuf.Serializer.Serialize<Item>(stream, new Item
    {
        Name = "kpatel",
        Id = 5566677,
        Value = 1234
    });

    var data = stream.ToArray();
    var content = new ByteArrayContent(data, 0, data.Length);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5163/api/item")
    {
        Content = content
    };

    var responseForPost = await client.SendAsync(request);
    var result = ProtoBuf.Serializer.Deserialize<Item[]>(await responseForPost.Content.ReadAsStreamAsync());

    Console.WriteLine("返回的值是:" + result[0].Name);
    Console.ReadLine();
}

客户端中的代码可以触发断点并返回预期的数据。

我想知道如何使用Postman来测试POST请求。

英文:

I would like to POST a request from postman with a protobuf message in the body, and hit the breakpoint in my service method, with the protobuf message deserialized to a c# object, but this is not happening. I get the following error in postman.

415 Unsupported media type

The GET request works correctly and hits the breakpoint in the service and returns data in protobuf format, but the POST does not even hit the breakpoint. I take the returned protobuf format and add it to the body of the POST to test the post, but this does not work.

Here is the service code for GET and POST.

 [ApiController]
public class ItemController : ControllerBase
{
    [HttpGet]
    [Produces(&quot;application/x-protobuf&quot;)]
    public IActionResult Get()
    {
        List&lt;Item&gt; items = new List&lt;Item&gt;
        {
            new Item{Id=1, Name= &quot;Item 1&quot;, Value=4},
            new Item{Id=2, Name= &quot;Item 2&quot;, Value=3 }
        };
        return Ok(items);
    }


    [HttpPost]
    [Consumes(&quot;application/x-protobuf&quot;, &quot;application/json&quot;)]
    [Produces(&quot;application/x-protobuf&quot;)]
    public IActionResult Post([FromBody]  Item myItem)
    {
        
        List&lt;Item&gt; items = new List&lt;Item&gt;
        {
            new Item{Id=1, Name= &quot;Item 5&quot;, Value=4},
            new Item{Id=2, Name= &quot;Item 7&quot;, Value=3 }
        };

        items.Add(myItem);
        return Ok(items);
    }
}

The model looks like this:

using ProtoBuf;

namespace ProtobufService
{
    [ProtoContract]
    public class Item
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
        [ProtoMember(3)]
        public long Value { get; set; }
    }
}

The libraries in the service project are...

使用POSTMAN发送一个包含Protobuf数据的请求

使用POSTMAN发送一个包含Protobuf数据的请求

使用POSTMAN发送一个包含Protobuf数据的请求

使用POSTMAN发送一个包含Protobuf数据的请求

I have written a console app which is a test client. This client performs the GET and POST correctly and breakpoints are getting hit. Here is the code for the client...

 private static async Task GetProtobufData(HttpClient client)
 {       
    var request = new HttpRequestMessage(HttpMethod.Get, &quot;http://localhost:5163/api/item&quot;);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/x-protobuf&quot;));
    var result = await client.SendAsync(request);
    var tables = ProtoBuf.Serializer.Deserialize&lt;Item[]&gt;(await result.Content.ReadAsStreamAsync());


    string itemproto = Serializer.GetProto&lt;Item&gt;();
    Console.WriteLine(itemproto);

    Console.WriteLine(&quot;the returned from get value is: &quot; + tables[1].Name);
    Console.ReadLine();
}

private static async Task PostProtobufData(HttpClient client)
{
    MemoryStream stream = new MemoryStream();
    ProtoBuf.Serializer.Serialize&lt;Item&gt;(stream, new Item
    {
        Name = &quot;kpatel&quot;,
        Id=5566677,
        Value=1234
    });
    
    var data = stream.ToArray();
    var content = new ByteArrayContent(data, 0, data.Length);
    content.Headers.ContentType = new MediaTypeHeaderValue(&quot;application/x-protobuf&quot;);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, &quot;http://localhost:5163/api/item&quot;)
    {
        Content = content
    };

    var responseForPost = await client.SendAsync(request);
    var result = ProtoBuf.Serializer.Deserialize&lt;Item[]&gt;(await responseForPost.Content.ReadAsStreamAsync());

    Console.WriteLine(&quot;the returned value is: &quot; + result[0].Name);
    Console.ReadLine();
}

The code in the client is hitting the breakpoints and returning expected data.

I would like to know how to test a POST using postman.

答案1

得分: 0

我通过将ContentType从参数移至Headers选项卡,并将从Get请求中获取的protobuf响应粘贴到服务端点的参数中来解决了这个问题。

参数选项卡现在看起来像这样...

使用POSTMAN发送一个包含Protobuf数据的请求

Headers选项卡...

使用POSTMAN发送一个包含Protobuf数据的请求

在端点参数中使用raw的请求体...

使用POSTMAN发送一个包含Protobuf数据的请求

来自服务端点的JSON响应...

使用POSTMAN发送一个包含Protobuf数据的请求

断点和请求参数反序列化...

使用POSTMAN发送一个包含Protobuf数据的请求

英文:

I resolved this by moving the ContentType from params to Headers tab, and pasting in the protobuf response from the Get into the body (raw) as a parameter for my service endpoint.

the param tab now looks like...

使用POSTMAN发送一个包含Protobuf数据的请求

the headers tab...

使用POSTMAN发送一个包含Protobuf数据的请求

the body using raw for endpoint param...
使用POSTMAN发送一个包含Protobuf数据的请求

the response from service endpoint in json...

使用POSTMAN发送一个包含Protobuf数据的请求

The breakpoint and the request param deserialized...

使用POSTMAN发送一个包含Protobuf数据的请求

huangapple
  • 本文由 发表于 2023年3月9日 17:21:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定