Xamarin - 使用BsonMediaTypeFormatter发布请求

时间:2016-02-28 16:39:31

标签: c# asp.net-web-api xamarin

我想发布http请求以使用BSON格式调用WebAPI,如下所示:

using (var client = new HttpClient())
{                
    // Post data as BSON format
    var bsonFormatter = new BsonMediaTypeFormatter();
    var response = await client.PostAsync(url, data, bsonFormatter);
}

它适用于.Net framework 4.5。

然而,它不适用于Xamarin Android平台,因为它不支持BsonMediaTypeFormatter类型。

所以问题是如何让它与Xamarin平台一起使用?

2 个答案:

答案 0 :(得分:0)

您需要找到兼容Xamarin的BSON(反)串行器,并在发送之前使用它来序列化数据。像这样:

var content = BsonSerializer.Serialize(data);
var response = await client.PostAsync(
    url, 
    new StringContent(content, Encoding.UTF8, "application/bson"));

例如,Json.NET似乎支持BSON数据。当然,如果使用BSON过于复杂,你总是可以在Xamarin项目中使用JSON。

答案 1 :(得分:0)

我最终使用以下解决方案将ByteArrayContentContent-Type标题一起使用:

public static async HttpResponseMessage PostBson<T>(string url, T data)
{    
            using (var client = new HttpClient())
            {
                //Specifiy 'Accept' header As BSON: to ask server to return data as BSON format
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/bson"));                    

                //Specify 'Content-Type' header: to tell server which format of the data will be posted
                //Post data will be as Bson format                
                var bSonData = HttpExtensions.SerializeBson<T>(data);
                var byteArrayContent = new ByteArrayContent(bSonData);
                byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");

                var response = await client.PostAsync(url, byteArrayContent);

                response.EnsureSuccessStatusCode();

                return response;
            }           
}

使用BSON data帮助序列化JSON.Net的方法:

public static byte[] SerializeBson<T>(T obj)
{
            using (MemoryStream ms = new MemoryStream())
            {
                using (BsonWriter writer = new BsonWriter(ms))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, obj);
                }

                return ms.ToArray();                
            }
 }