ojhawkins
ojhawkins

Reputation: 3298

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[]?

Upvotes: 3

Views: 5576

Answers (3)

zhimin
zhimin

Reputation: 3050

First, install nuget package Microsoft.AspNet.WebApi.Client ;

Then use the generic extension method of http content:

c# var result = await response.Content.ReadAsAsync<byte[]>();

It should works!

Upvotes: 1

Vano Maisuradze
Vano Maisuradze

Reputation: 5899

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);
        }
    }
}

Upvotes: 5

Nathan Smith
Nathan Smith

Reputation: 1813

You can return binary data from a Web Api method. The ms object is a memory stream You might want to set a more specific ContentType

On the server:

var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;

Then on the client:

response.Content.ReadAsByteArrayAsync();

Upvotes: 3

Related Questions