Transfer raw bytes through http using ASP.Net WebAPI 2

I have a very simple ASP.Net WebAPI 2 method, which I hope will send a small array of bytes via 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 replaced the assigned code (remembered above) with a simple array containing byte 0x20 seven times. To check 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 a webpage to see which bytes or text were added to the beginning or 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) doesn't even appear once.

(NB . -, .Net Micro Framework, ( ) WebAPI.)

? HTTP ASP.Net WebAPI?

+2
1

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;
+6

Source: https://habr.com/ru/post/1674152/


All Articles