我正在尝试找出正确的&从返回byte []的Asp.Net Web Api方法反序列化响应的最佳方法。
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[]
?
答案 0 :(得分:4)
我会使用json.net。
Web 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);
}
}
}
答案 1 :(得分:3)
您可以从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();
答案 2 :(得分:1)
首先,安装nuget package Microsoft.AspNet.WebApi.Client
;
然后使用http内容的通用扩展方法:
c#
var result = await response.Content.ReadAsAsync<byte[]>();
它应该有效!