How to Use Google's Protocol Buffers in C#

By FoxLearn 7/10/2024 7:19:27 AM   4.83K
Using Protocol Buffers (Protobuf) in ASP.NET Core Web API involves a few steps to set up, including defining your messages, generating C# classes from those messages, and integrating them into your API controllers.

The protocol buffer also known as protobuf is a language-neutral, it's basically used to serialized objects. It stores structured data that can be Serialized or DeSerialized automatically by many different languages. It's designed to be a language / platform neutral and extensible.

c# protobuf

The advantages of Protobuf is very fast serialization and deserialization. Moreover, the data size is much smaller than that of xml or json format. In the scope of this article, I will guide you how to use Protobuf.net in ASP.NET Core.

Here’s a step-by-step guide on How to Use Google's Protocol Buffers in C#

Creating a new ASP.NET Core project, then select Web Api template.

After you finish creating your project, you need to install protobuf-net framework by right-clicking on your project, then select Manage Nuget Packages from the Visual Studio.

You need to search and install WebApiContrib.Core.Formatter.Protobuf to your project.

WebApiContrib.Core.Formatter.Protobuf

This google protobuf-net core library support ASP.NET Core InputFormatter, OutputFormatter for Protobuf.

Creating an Item class a show below.

ASP.NET Core protobuf formatter

[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; }
}

and don't forget to include namespace

using ProtoBuf;

Opening your Startup class, then modify your code as shown below.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddProtobufFormatters();
}

You can now use Protocol Buffers in your API controllers. Create an ItemController, then modify your code as shown below.

[Route("api/[controller]")]
[Produces("application/x-protobuf")]
[ApiController]
public class ItemController : ControllerBase
{
    [HttpGet]
    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);
    }
}

By default, your code will be returned json data when calling HttpGet. You should set [Produces("application/x-protobuf")] to ensure that your method returns the Protobuf data.

You can use Postman software to test demo or create a console application.

c# restsharp protobuf

Right-click on your console application, then select Manage Nuget Packages. Search for protobuf-net, protobuf-net.Core and RestSharp and Install libraries to your project.

The RestSharp is a free open source library that make it easy to consume RESTful services.

Copying the Item class you created in the ASP.NET Core project into Console Application project.

class Program
{
    static void Main(string[] args)
    {
        RestClient client = new RestClient("http://localhost:2179/");
        client.AddDefaultHeader("Content-Type", "application/x-protobuf");
        RestRequest request = new RestRequest("api/item", Method.GET);
        var response = client.Execute(request);
        using (var stream = new MemoryStream(response.RawBytes))
        {
            var items = Serializer.Deserialize<List<Item>>(stream);
            foreach(Item item in items)
                 Console.WriteLine($"{item.Name}");
        }
        Console.ReadLine();
    }
}

You can also use HttpClient to handle Web Api in C#, and don't forget to install the WebApiContrib.Formatting.ProtoBuf to your console application.

//google protobuf deserialize c#
class Program
{
    static void Main(string[] args)
    {
        var client = new HttpClient { BaseAddress = new Uri("http://localhost:2179/") };
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
        HttpResponseMessage response = client.GetAsync("api/item").Result;
        if (response.IsSuccessStatusCode)
        {
            List<Item> items = response.Content.ReadAsAsync<List<Item>>(new[] { new ProtoBufFormatter() }).Result;
            foreach (Item item in items)
                Console.WriteLine($"{item.Name}");
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }
    }
}

By following these steps, you can easily integrate Protocol Buffers into your ASP.NET Core Web API in C#.

Related