webapi 中使用 protobuf

相比json来说,好处是速度更快,带宽占用更小。其效果大致等于json+Gzip。

在webapi中使用protobuf的方法为:

 

引用nuget包

Install-Package protobuf-net

 

为DTO添加注解 

    [ProtoContract]
    public class Product
    {

        [ProtoMember(1)]
        public int Id { get; set; }


        [ProtoMember(2)]
        public string Name { get; set; }


        [ProtoMember(3)]
        public long Value { get; set; }

    }

 

 

 注册MediaTypeFormatter

在WebApiConfig文件中添加黄色部分的代码

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由  config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // config.Formatters.Clear(); config.Formatters.Add(new ProtoBufFormatter()); } }

 

调用接口

http请求报文

GET http://test.cn/webapi/api/product/123 HTTP/1.1
Host: localhost:44605
Connection: keep-alive
Accept: application/x-protobuf

注意黄色的部分

 httpclient请求

            string url = "http://test.cn/webapi/api/product/123";

            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage();
       
            request.RequestUri = new Uri(url);
            request.Method = HttpMethod.Get;
            request.Headers.Add("Accept", "application/x-protobuf");

            HttpResponseMessage result = client.SendAsync(request).Result;

            var stream = result.Content.ReadAsStreamAsync().Result;

            var product= Serializer.Deserialize<Product>(stream);

 

转载于:https://www.cnblogs.com/dehai/p/5043240.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值