Post byte array to Web API server using HttpClient

后端 未结 4 1598
执念已碎
执念已碎 2020-11-30 07:14

I want to post this data to Web API server:

public sealed class SomePostRequest
{
    public int Id { get; set; }
    public byte[] Content { get; set; }
}
<         


        
4条回答
  •  误落风尘
    2020-11-30 08:14

    I have created this generic and cross platform method to support the BSON format using the Json.NET library so we can reuse it easier later. It works fine in Xamarin platform as well.

    public static async HttpResponseMessage PostBsonAsync(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(data);
            var byteArrayContent = new ByteArrayContent(bSonData);
            byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
    
            var response = await client.PostAsync(url, byteArrayContent);
    
            response.EnsureSuccessStatusCode();
    
            return response;
        }
    }
    

    The method to help to serialise data to BSON format:

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

    Then you can use the Post method like this:

    var response = await PostBsonAsync("api/SomeData/Incoming", requestData);
    

提交回复
热议问题