如何在C#中获取缓冲区的二进制数据?
item = {[_buffer, JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXR]}
我尝试了这个但收到错误:
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var dataStream = response.Content.ReadAsStringAsync().Result;
var parsed = JObject.Parse(dataStream);
if (dataStream == null)
return HttpNotFound();
foreach (dynamic item in parsed)
{
// If user decides to save the file, this will help...
Response.AddHeader("content-disposition", "filename=" + Path.GetFileName(fileDoc));
return File(item._buffer, "application/pdf");
}
}
答案 0 :(得分:1)
假设您的原始JSON看起来像这样:
{
"_buffer": "JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXRlIChEOjIwMTgwMTI2MjI0ODI1LTA1JzAwJykKL01vZERhdGUgKEQ6MjAxODAxMjYyMjQ4MjUtMDUnMDAnKQovUHJvZHVjZXIgKEJDTCBlYXN5UERGIDcuMDAgXCgwMzU1XCkpCi9DcmVhdG9yIChlYXN5UERGIFNESyA3IDcuMCkKPj4KZW5kb2JqCgo4"
}
然后“_buffer”属性的值似乎是Base64编码的二进制。正如其serialization guide中所述,Json.NET支持自动将Base64字符串反序列化为byte []
。因此你可以这样做:
var _buffer = JsonConvert.DeserializeAnonymousType(dataStream, new { _buffer = (byte[])null })._buffer;
然后将返回的字节数组传递给Controller.File(Byte[], String)
。
通过使用JsonConvert.DeserializeAnonymousType()
,您可以避免将(可能很大的)响应加载到中间JToken
层次结构中,并且还可以避免创建一个显式的具体类型来反序列化单个{{3}} {1}}属性。