dum*_*dad 2 c# asp.net-web-api
我有一个非常简单的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 };
}
Run Code Online (Sandbox Code Playgroud)
为了测试函数,我用一个包含字节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>
Run Code Online (Sandbox Code Playgroud)
我希望使用该网页来查看在字节数组的开头或结尾添加了哪些字节或文本.但相反,我看到这个和字节返回到网页:
73,67,65,103,73,67,65,103,73,65,61,61
Run Code Online (Sandbox Code Playgroud)
所以我的0x20(十进制的32)甚至没有出现一次.
(NB这似乎是一个人为的例子.实际的客户端不是一个网页,而是一个.Net Micro Framework嵌入式设备,它将(我希望)从WebAPI下载小动态程序集作为字节数组.)
我有什么错误或遗漏?使用ASP.Net WebAPI通过HTTP传输字节数组的最佳方法是什么?
如果您不返回a HttpResponseMessage,WebAPI会根据Accept标头和已安装的媒体类型格式化程序将值序列化为某种格式(JSON,XML等).
要发送原始数据:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new ByteArrayContent(bytes);
return res;
Run Code Online (Sandbox Code Playgroud)
或者,因为你有一个Stream:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new StreamContent(File.Open(...));
return res;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3467 次 |
| 最近记录: |