从 ASP Web Api IHttpActionResult 反序列化 byte[]

Deserialize byte[] from ASP Web Api IHttpActionResult

我正在尝试找出正确且最好的方法来反序列化 Asp.Net Web Api 方法的响应 returns byte[].

Web Api 方法如下所示

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

我正在调用端点

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

当我将响应读入 content 时,它的格式如下

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

将此响应转换为 byte[] 的最佳做法是什么?

您可以 return 来自 Web Api 方法的二进制数据。 ms对象是一个内存流 您可能想要设置更具体的 ContentType

在服务器上:

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

然后在客户端:

response.Content.ReadAsByteArrayAsync();

我会为此使用 json.net

网络API:

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

客户:

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

首先,安装 nuget 包 Microsoft.AspNet.WebApi.Client ;

然后使用http内容的通用扩展方法:

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

它应该有效!