iowatiger08
iowatiger08

Reputation: 1962

Support for Protobuf-net with requests in Web Api

I have a web api that I created and is able to take a JSON object post so long as the object Content-Type is application/json. We want to use protobuf from mobile devices to send data to the web api. If I switch the Content-type to x-protobuf and despite having this formatter added to my WebApiConfig

        config.Formatters.Add(new ProtoBufFormatter());

When I use the Chrome extension "Advanced Rest Client" or Fiddler, it looks like the Web Api will send out a serialized response when I do a Get, but I do not see it receiving the post request when set to protobuf.

The test method header from the Controller class looks like this so far:

   [HttpPost]
    public override async Task<LoginResponse> Post([FromBody]LoginRequest request)
    {...}

What more do I need to ensure that my WebApi will de-serialize the protobuf-serialized request.

What do you need to see to help? Please and thank you for your consideration.

Upvotes: 5

Views: 5844

Answers (2)

iowatiger08
iowatiger08

Reputation: 1962

The client has to send the request with protobuf serialization. Advanced Rest Client (or Fiddler) does not serialize the object. I wrote a test harness client that serialized the object like

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;

Upvotes: 4

Christian Findlay
Christian Findlay

Reputation: 7692

Here is an example with proto definition, back-end and front-end code with RestClient.Net.

Proto definition

message Person {
  string PersonKey = 1;
  string FirstName = 2;
  string Surname=3;
  Address BillingAddress = 4;
}

message Address {
  string AddressKey = 1;
  string StreeNumber = 2;
  string Street=3;
  string Suburb=4;
}

Code Reference

Controller:

[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var person = new Person
        {
            FirstName = "Sam",
            BillingAddress = new Address
            {
                StreeNumber = "100",
                Street = "Somewhere",
                Suburb = "Sometown"
            },
            Surname = "Smith"
        };

        var data = person.ToByteArray();

        return File(data, "application/octet-stream");
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var stream = Request.BodyReader.AsStream();
        return File(stream, "application/octet-stream");
    }

    [HttpPut]
    public async Task<IActionResult> Put()
    {
        var stream = Request.BodyReader.AsStream();

        var person = Person.Parser.ParseFrom(stream);

        if (!Request.Headers.ContainsKey("PersonKey")) throw new Exception("No key");

        person.PersonKey = Request.Headers["PersonKey"];

        var data = person.ToByteArray();

        return File(data, "application/octet-stream");
    }
}

Code Reference

Serialization:

public class ProtobufSerializationAdapter : ISerializationAdapter
{
    public byte[] Serialize<TRequestBody>(TRequestBody value, IHeadersCollection requestHeaders)
    {
        var message = (IMessage)value as IMessage;           
        if (message == null) throw new Exception("The object is not a Google Protobuf Message");
        return message.ToByteArray();
    }

    public TResponseBody Deserialize<TResponseBody>(byte[] data, IHeadersCollection responseHeaders)
    {
        var messageType = typeof(TResponseBody);
        var parserProperty = messageType.GetProperty("Parser");
        var parser = parserProperty.GetValue(parserProperty);
        var parseFromMethod = parserProperty.PropertyType.GetMethod("ParseFrom", new Type[] { typeof(byte[]) });
        var parsedObject = parseFromMethod.Invoke(parser,new object[] { data });
        return (TResponseBody)parsedObject;
    }
}

Code Reference

Usage:

          var person = new Person { FirstName = "Bob", Surname = "Smith" };
          var client = new Client(new ProtobufSerializationAdapter(), new Uri("http://localhost:42908/person"));
          person = await client.PostAsync<Person, Person>(person);

Code Reference

Upvotes: -1

Related Questions