What do I need to do to send out Protobuf serialized Data using C# ASP .NET web api?

不羁的心 提交于 2019-12-11 11:22:54

问题


I'm new to protobuf and fairly new to asp .net. so I might need help on this. I have this code snippet for my PersonsController:

public class PersonController : ApiController
{
    [ProtoContract]
    public class Person
    {
        [ProtoMember(1)]
        public int ID { get; set; }
        [ProtoMember(2)]
        public string First { get; set; }
        [ProtoMember(3)]
        public string Last { get; set; }
    }
    // GET api/values
    public IEnumerable<Person> Get()
    {
        List<Person> myList = new List<Person> { 
            new Person { ID = 0, First = "Judy", Last  = "Lee" },
            new Person { ID = 1, First = "John", Last  = "Doe" },
            new Person { ID = 2, First = "George", Last  = "Poole" },
        };

        return myList;
    }
}

and I'm wondering if that's enough to be able to send out the protobuf data and be consumed by other applications?

I'm trying to access it directly in google chrome and all I'm getting is an XML format of the data.

<ArrayOfPersonController.Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/SampleSerialize.Controllers">
  <PersonController.Person>
    <First>Judy</First>
    <ID>0</ID>
    <Last>Lee</Last>
  </PersonController.Person>
  <PersonController.Person>
    <First>John</First>
    <ID>1</ID>
    <Last>Doe</Last>
  </PersonController.Person>
  <PersonController.Person>
    <First>George</First>
    <ID>2</ID>
    <Last>Poole</Last>
  </PersonController.Person>
</ArrayOfPersonController.Person>

How do I know if I'm able to send out the serialized data?


回答1:


You'll need to do a couple of things:

  1. You need a web client that actually asks for protobuf-serialized content in the request's Accept header. Chrome doesn't do this--it only asks for things like text/html, image/*, etc... stuff you'd expect a web browser to ask for. There isn't a standard content type for protobuf, so you can just define your own--many people use application/x-protobuf. There are Chrome developer tools like Advanced REST client that let you exercise REST APIs from a browser and set your request headers however you'd like.

  2. On the Web API side, you need to create and register your own media formatter. There's a good walkthrough here. You'll probably derive from BufferedMediaTypeFormatter to do the protobuf (de/)serialization, and you'll want to configure this class to handle application/x-protobuf requests. Then you'll need to register it with the Web API pipeline.



来源:https://stackoverflow.com/questions/35348747/what-do-i-need-to-do-to-send-out-protobuf-serialized-data-using-c-sharp-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!