MVC 或 Web API 传输 byte[] 最高效的方法

MVC or Web API transfer byte[] the most efficient approach

成功实现 ajax POST 后,上传模型对象甚至复杂对象都归功于此 nice post, 新的目标是为更复杂的场景提供一个实现。

我已尝试通过代码示例搜索 google 来实现相关任务,但没有具体和正确的答案

目标是从客户端到服务器(不使用表单或 HttpRequestBase)进行多用途(多数据类型)数据传输可以实施新协议 HTTP/2 或 googles Protocol Buffers - Google's data interchange format

[HttpPost]
public JsonResult UploadFiles(byte[] parUploadBytearry)
{
}

最好是其中一个属性是 byte[]

的模型
[HttpPost]
public [JsonResult / ActionResult] Upload(SomeClassWithByteArray parDataModel)
{
}

ajaxhttpPost签名:

Log("AajaxNoPostBack preparing post-> " + targetUrl);
$.ajax({
    type: 'POST',
    url: targetUrl,
    data: mods,
    contentType: "application/json; charset=utf-8",
    dataType: "json",

    success:  function for Success..
});

我也拼命尝试过这个解决方法

public JsonResult UploadFiles(object parUploadBytearry)
{
    if (parUploadBytearry== null)
        return null;
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    var pathtosSave = System.IO.Path.Combine(Server.MapPath("~/Content/uploaded"), "Test11.png");
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        bf.Serialize(ms, parUploadFiles);
        var Barr =  ms.ToArray();
        var s = new System.Web.Utils.FileFromBar(pathtosSave, BR);
    }
}

因为它post并且一直接收数据到将数据(.png)成功保存到系统中的文件,数据不合法。

在对象到字节数组尝试之前的最后一次正常尝试是这个 msdn Code example 1

传递 C# 能够理解的字节数组的正确方法是什么?

(如果是文档 raw byte[] 或像 png 图片这样的文件)

What is the correct way to pass a byte array

从 WebAPI 读取 byte[] 而无需为 "application/octet-stream" 编写自定义 MediaTypeFormatter 的最简单方法是手动从请求流中读取它:

[HttpPost]
public async Task<JsonResult> UploadFiles()
{
    byte[] bytes = await Request.Content.ReadAsByteArrayAsync();
}

中,我描述了如何使用 WebAPI 2.1 中存在的 BSON(二进制 JSON)内置格式化程序。

如果您确实想要阅读和编写一个回答 "application/octet-stream" 的 BinaryMediaTypeFormatter,一个天真的实现将如下所示:

public class BinaryMediaTypeFormatter : MediaTypeFormatter
{
    private static readonly Type supportedType = typeof(byte[]);

    public BinaryMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
    }

    public override bool CanReadType(Type type)
    {
        return type == supportedType;
    }

    public override bool CanWriteType(Type type)
    {
        return type == supportedType;
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
        HttpContent content, IFormatterLogger formatterLogger)
    {
        using (var memoryStream = new MemoryStream())
        {
            await stream.CopyToAsync(memoryStream);
            return memoryStream.ToArray();
        }
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream stream,
        HttpContent content, TransportContext transportContext)
    {
        if (value == null)
            throw new ArgumentNullException("value");
        if (!type.IsSerializable)
            throw new SerializationException(
                $"Type {type} is not marked as serializable");

        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(stream, value);
        return Task.FromResult(true);
    }
}

答案是正确的,但我在 visual studio 2019 中使用 asp.net mvc,似乎根本没有 Request.Content 的定义,这是错误:

“HttpRequest”不包含“Content”的定义,并且找不到接受“HttpRequest”类型的第一个参数的可访问扩展方法“Content”。

然后我使用了这种方法,它对我有用:

  Request.InputStream.Position = 0;
    List<byte> bytelist = new List<byte> { };

    while (Request.InputStream.Position != Request.InputStream.Length)
    {
        bytelist.Add((byte)Request.InputStream.ReadByte());
    }

希望有用والله اعلم