WebApi2官网学习记录---BSON

BSON 是轻量级的,能够进行快速查询和高效的解码/编码。BSON方便查询是由于elements的前面都有一个表示长度的字段,所以解释器可以快速跳过这个elements;高效的解码/编码是因为numeric数据直接存储为numbers,不用转为string。

在服务端启用BSON  

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Add(new BsonMediaTypeFormatter());

        // Other Web API configuration not shown...
    }
}
View Code

  如果client的请求是“application/bson”,webapi将使用BSON的序列化器。

 可以将其它的media type也使用BSON就行序列化,如下:  

var bson = new BsonMediaTypeFormatter();
bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
config.Formatters.Add(bson);

使用HttpClient模拟BSON请求  

 1 static async Task RunAsync()
 2 {
 3     using (HttpClient client = new HttpClient())
 4     {
 5         client.BaseAddress = new Uri("http://localhost");
 6 
 7         // Set the Accept header for BSON.
 8         client.DefaultRequestHeaders.Accept.Clear();
 9         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
10 
11         // Send GET request.
12         result = await client.GetAsync("api/books/1");
13         result.EnsureSuccessStatusCode();
14 
15         // Use BSON formatter to deserialize the result.
16         MediaTypeFormatter[] formatters = new MediaTypeFormatter[] {
17             new BsonMediaTypeFormatter()
18         };
19 
20         var book = await result.Content.ReadAsAsync<Book>(formatters);
21     }
22 }
View Code

序列化原生的类型

   BSON的文档都是key/value的集合,BSON的规范并没有定义只返回一个原生值的语法,如返回一个int或string类型的值。

为了解决这个问题BsonMediaTypeFormatter将原生的类型特殊对待,在序列化前,将其转为key/value形式,key是"Value".如下:

public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        return Ok(42);
    }
}
返回值:
{ "Value": 42 }

  当反序列化时,序列化器将数据转为原始的值。当然如果使用其它的BSON序列化器,如果服务端返回这样类型的数据,BSON解析器需要处理这种情况。 

原文地址:https://www.cnblogs.com/goodlucklzq/p/4451191.html