ASP. NET Core cross-platform development from entry to practice Web API custom formatting protobuf,

Source: Internet
Author: User

ASP. NET Core cross-platform development from entry to practice Web API custom formatting protobuf,

In the sample section of ASP. NET Core cross-platform development from getting started to practice, you can customize and format protobuf using Web APIs.

Example

Protocol Buffers is a lightweight and efficient structured data storage format that can be used for serialization or serialization of structured data.

It is suitable for data storage or RPC data exchange formats. It can be used for language-independent, platform-independent, and scalable serialized structure data formats in communication protocols, data storage, and other fields.

The following describes how to implement a formatter to return the protobuf format.

Create an ASP. NET Core Web Application named ProtobufFormat and select the Web API template.

Add protobuf-net reference. Use the NuGet command line or the NuGet Package Manager for installation.

NuGet command line: Install-Package protobuf-net.

Add a ProtobufFormatter class

Public class ProtobufFormatter: OutputFormatter

{

Public string ContentType {get; private set ;}

Public ProtobufFormatter ()

{

ContentType = "application/proto ";

SupportedMediaTypes. Add (Microsoft. Net. Http. Headers. MediaTypeHeaderValue. Parse ("application/proto "));

}

 

Public override Task WriteResponseBodyAsync (OutputFormatterWriteContext context)

{

If (context = null)

{

Throw new ArgumentNullException (nameof (context ));

}

Var response = context. HttpContext. Response;

Serializer. Serialize (response. Body, context. Object );

Return Task. FromResult (0 );

}

}

Inherit OutputFormatter, and then implement the WriteResponseBodyAsync method. The ContentType value is assigned during initialization and MediaType is added.

Obtain Response in the WriteResponseBodyAsync method and call the Serialize method of protobuf-net to Serialize the Object to the output content. Protobuf must specify the sequence during serialization, otherwise the serialization will fail.

 

Add a User class to implement protobuf objects.

 

[ProtoContract]

Public class User

{

[ProtoMember (1)]

Public int Id {get; set ;}

[ProtoMember (2)]

Public string Name {get; set ;}

[ProtoMember (3)]

Public int Age {get; set ;}

}

 

Class requires the ProtoContract feature, and then the field requires the ProtoMember feature, and specify the order. Such a class can be serialized to the protobuf format.

 

Then, modify the operations in the ValuesController to output protobuf.

 

[Route ("api/[controller]")]

Public class ValuesController: Controller

{

Private IEnumerable <User> Users;

Public ValuesController ()

{

Users = new User [] {

New User () {Id = 1, Name = "book", Age = 1 },

New User () {Id = 2, Name = "asp.net core", Age = 10 },

};

}

// GET api/values

[HttpGet]

[Produces ("application/proto")]

Public IEnumerable <User> Get ()

{

Return Users;

}

 

// GET api/values/5

[HttpGet ("{id}")]

[Produces ("application/proto")]

Public User Get (int id)

{

Return Users. FirstOrDefault (r => r. Id = id );

}

}

 

Add the Produces feature to each operation. The nominal value is application/proto, that is, the configured ContentType. Then you can directly return the corresponding object result.

If you run the application now, access api/values and you will find that no result is returned, because you also need to add the corresponding formatting in AddMvc.

Open the ConfigureServices method in the Startup class and change services. AddMvc () to the following:

Public void ConfigureServices (IServiceCollection services)

{

Services. AddMvc (option => {

Option. OutputFormatters. Add (new ProtobufFormatter ());

});

}

 

Add the output formatter ProtobufFormatter.

Run the application again. Accessing api/values will return a binary file containing serialized data.

 

You can create a new test program to simulate calling Web APIs to check whether serialization is correct.

Create a. NET Core console application and change the Main method to the following code in Program. cs:

 

Public static void Main (string [] args)

{

HttpClient client = new HttpClient ();

Var stream = client. GetStreamAsync ("http: // localhost: 5000/api/values"). Result;

Var users = Serializer. Deserialize <List <User> (stream );

Foreach (var item in users)

{

Console. WriteLine ($ "ID: {item. Id}-Name: {item. Name}-Age: {item. Age }");

}

Console. ReadKey ();

}

 

And copy the User class to the project.

The Code is to access http: // localhost: 5000/api/values to obtain the result and deserialize it into an object. Traverse the object and display it.

First, run the Web API application and then the test console application. The console application is displayed as follows:

 

ID: 1-Name: book-Age: 1

ID: 2-Name: asp.net core-Age: 10

 

The object is successfully accessed and deserialized. In this way, the custom formatter ProtobufFormatter is successfully implemented. Similarly, other formatting programs can be implemented.

 

Perception

 

ASP. NET Core cross-platform development from entry to practice has been successfully published for quite a long time. This book is Based on. NET Core 1.0.

. NET Core is developing rapidly, and now the new VS2017 is also released. As a result, some content in the book may not be applicable. However, the theoretical part and Code are not outdated.

This book is positionedGetting started with ASP. NET Core and learningASP. NET Core is helpful.

You can click the purchase link at the bottom of the article or on the left to view detailed directories and purchases.

Activity

Book-giving activity.6ASP. NET Core cross-platform development from entry to practice.

Activity Rules:

Comment below or forward it to Weibo and comment below.

Winning floor rules:

DeadlineApril 21Number of floors -(Number of floors/6-1) decrease. For example:Final 50-layer 50-(50/6-1) = 43 43-7 = 36 36-7 = 29 29-7 = 22 22-7 = 15 15-7 = 8

Each person can comment for a maximum of three times. If the comment is greater than the comment, the comment will be postponed to the next one.

Published at on March 13, April 21After the prize is announced, you will trust me in your address and contact information.

 

If you think this article is helpful to you, click"Recommendation", Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.