Post byte array to Web API server using HttpClient

后端 未结 4 1601
执念已碎
执念已碎 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 07:55

    WebAPI v2.1 and beyond supports BSON (Binary JSON) out of the box, and even has a MediaTypeFormatter included for it. This means you can post your entire message in binary format.

    If you want to use it, you'll need to set it in WebApiConfig:

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

    Now, you an use the same BsonMediaTypeFormatter at the client side to serialize your request:

    public async Task SendRequestAsync()
    {
        var client = new HttpClient
        {
            BaseAddress = new Uri("http://www.yourserviceaddress.com");
        };
    
        // Set the Accept header for BSON.
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/bson"));
    
        var request = new SomePostRequest
        {
            Id = 20,
            Content = new byte[] { 2, 5, 7, 10 }
        };
    
        // POST using the BSON formatter.
        MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
        var result = await client.PostAsync("api/SomeData/Incoming", request, bsonFormatter);
    
        result.EnsureSuccessStatusCode();
    }
    

    Or, you can use Json.NET to serialize your class to BSON. Then, specify you want to use "application/bson" as your "Content-Type":

    public async Task SendRequestAsync()
    {   
        using (var stream = new MemoryStream())
        using (var bson = new BsonWriter(stream))
        {
            var jsonSerializer = new JsonSerializer();
    
            var request = new SomePostRequest
            {
                Id = 20,
                Content = new byte[] { 2, 5, 7, 10 }
            };
    
            jsonSerializer.Serialize(bson, request);
    
            var client = new HttpClient
            {
                BaseAddress = new Uri("http://www.yourservicelocation.com")
            };
    
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/bson"));
    
            var byteArrayContent = new ByteArrayContent(stream.ToArray());
            byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
    
            var result = await client.PostAsync(
                    "api/SomeData/Incoming", byteArrayContent);
    
            result.EnsureSuccessStatusCode();
        }
    }
    

提交回复
热议问题