Reputation: 17527
I have a very simple ASP.Net WebAPI 2 method that I hoped would send a small array of bytes over 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 };
}
To test the function I have replaced the intended code (commented out in the above) with a simple array containing the byte 0x20 seven times. To test my code I have a simple web page:
<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>
I was hoping to use the web page to see what bytes or text were added to the beginning or the end of the byte array. But instead I see this and the bytes returned to the web page:
73,67,65,103,73,67,65,103,73,65,61,61
So my 0x20 (32 in decimal) does not even show up once.
(N.B. This may seem a contrived example. The actual client will not be a web page but a .Net Micro Framework embedded device that will (I hope) download small dynamic assemblies as byte arrays from the WebAPI.)
What have I got wrong or omitted? What is the best way to transfer an array of bytes over HTTP using the ASP.Net WebAPI?
Upvotes: 2
Views: 4031
Reputation: 29981
If you do not return a HttpResponseMessage
, WebAPI will serialize the value into some format (JSON, XML, etc.) depending on Accept headers and installed media type formatters.
To send raw data:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new ByteArrayContent(bytes);
return res;
Or, since you have a Stream
:
HttpResponseMessage res = CreateResponse(HttpStatusCode.OK);
res.Content = new StreamContent(File.Open(...));
return res;
Upvotes: 6