我有一个非常简单的ASP.Net WebAPI 2方法,希望通过HTTP发送一小部分字节:
[Route("api/assemblybytes")]
public byte[] GetAssemblyBytes()
{
//byte[] bytes = null;
//if (File.Exists("BasePCBScreenAssembly.dll"))
//{
// using (var fs = File.Open("BasePCBScreenAssembly.dll", FileMode.Open, FileAccess.Read))
// {
// fs.Read(bytes, 0, (int)fs.Length);
// }
//}
//return bytes;
return new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
}
为了测试该功能,我已经用包含字节0x20的简单数组替换了预期的代码(在上面进行了注释)七次。要测试我的代码,我有一个简单的网页:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Assembly Distribution WebAPI Test Page</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/assemblybytes';
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
var bytes = [];
for (var i = 0; i < data.length; ++i) {
bytes.push(data.charCodeAt(i));
}
$('#AssemblyBytes').text(bytes)
});
});
</script>
</head>
<body>
<div>
<h2>GetAssemblyBytes</h2>
<pre id='AssemblyBytes'/>
</div>
</body>
</html>
我希望使用该网页来查看将哪些字节或文本添加到字节数组的开头或结尾。但是相反,我看到了这一点,并将字节返回到了网页:
73,67,65,103,73,67,65,103,73,65,61,61
因此,我的0x20(十进制为32)甚至都不会显示一次。
(注意,这可能是一个人为的例子。实际的客户端不是网页,而是.Net Micro Framework嵌入式设备,它将(希望)从WebAPI下载小的动态程序集作为字节数组。)
我错了或遗漏了什么?使用ASP.Net WebAPI通过HTTP传输字节数组的最佳方法是什么?
如果不返回HttpResponseMessage
,则WebAPI会将值序列化为某种格式(JSON,XML等),具体取决于Accept标头和已安装的媒体类型格式化程序。
发送原始数据:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new ByteArrayContent(bytes);
return res;
或者,因为您有Stream
:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new StreamContent(File.Open(...));
return res;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句