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

כרמ*_*פאל 13 c# ajax asp.net-mvc bytearray asp.net-mvc-4

在成功实现ajax POST,上传模型对象甚至复杂对象之后,由于这个好帖子,新的目标是实现更复杂的场景.

我试图通过搜索谷歌的代码示例来实现有问题的任务,而没有具体和正确的答案

目标是从客户端到服务器的多用途(多数据类型)数据传输(不使用表单或HttpRequestBase)以最有效的方式传递原始字节数组(我知道可以实现新的协议HTTP/2或googles Protocol Buffers - 谷歌的数据交换格式

[HttpPost]
public JsonResult UploadFiles(byte[] parUploadBytearry)
{
}
Run Code Online (Sandbox Code Playgroud)

优选地,其中一个属性是a的模型 byte[]

[HttpPost]
public [JsonResult / ActionResult] Upload(SomeClassWithByteArray parDataModel)
{
}
Run Code Online (Sandbox Code Playgroud)

ajax http Post签名:

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

    success:  function for Success..
});
Run Code Online (Sandbox Code Playgroud)

我也拼命尝试了这种解决方法

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

因为它一直发布和接收数据以将data(.png)成功保存到系统中的文件,所以数据不合法.

在对象到字节数组尝试之前的最后一个理智尝试是这个msdn 代码示例1

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

(如果是文件raw byte[]或文件,如png图像)

Yuv*_*kov 3

传递字节数组的正确方法是什么

最简单的阅读方法byte[]是简单地从请求流中手动读取它:

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

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

如果您确实想继续读取并写入BinaryMediaTypeFormatter答案“application/octet-stream”,则简单的实现将如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)