Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize byte[] from ASP Web Api IHttpActionResult

I am trying work out the correct & best way to deserialize the response from a Asp.Net Web Api method that returns byte[].

The Web Api method looks like this

public IHttpActionResult Get()
{
    byte[] content = GetContent();
    return Ok(content);
}

I am calling the endpoint

string content;
using (var client =  new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

    HttpResponseMessage response = await client.GetAsync("api/v1/thecorrectpath");
    if (response.IsSuccessStatusCode)
    {
        content = await response.Content.ReadAsStringAsync();
    }
}

When I read the response into content it is in the format below

<base64Binary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">SfSEjEyNzE9MNgMCD2a8i0xLjcNJeLjzC...R4Cg==</base64Binary>

What would be a best practice way to convert this response into a byte[]?

like image 537
ojhawkins Avatar asked Jul 29 '26 21:07

ojhawkins


1 Answers

I would use json.net for this.

Web API:

public string Get()
{
    byte[] content = GetContent();
    var data = JsonConvert.SerializeObject(content);
    return data;
}

Client:

private static async Task GetData()
{
    string content;
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:23306/");
        client.DefaultRequestHeaders.Accept.Clear();

        HttpResponseMessage response = await client.GetAsync("home/get");
        if (response.IsSuccessStatusCode)
        {
            content = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<byte[]>(content);
        }
    }
}
like image 96
Vano Maisuradze Avatar answered Aug 01 '26 11:08

Vano Maisuradze