【问题标题】:MVC or Web API transfer byte[] the most efficient approachMVC 或 Web API 传输 byte[] 最有效的方法
【发布时间】:2016-06-28 08:03:14
【问题描述】:

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

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

我们的目标是让多用途(多数据类型)数据从客户端传输到服务器(不使用表单或HttpRequestBase)以最有效的方式传递原始字节数组(我知道这是可能的)实施新协议HTTP/2 或谷歌 Protocol Buffers - Google's data interchange format

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

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

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

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..
});

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

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);
    }
}

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

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

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

(如果是文件raw byte[]png 图像之类的文件)

【问题讨论】:

  • 在您的SomeClassWithByteArray 示例中,如果传输协议是JSON,您如何序列化字节数组? Base64?
  • 这也是一个选项,正如我在帖子开头所说的复杂对象,我使用了toDictionary 插件,我希望 原始数据,作为它的成员之一, 将是最简单的,然后以任何有效的方法进行转换

标签: c# ajax asp.net-mvc asp.net-mvc-4 bytearray


【解决方案1】:

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

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

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

another post 中,我描述了如何利用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);
    }
}

【讨论】:

  • WebAPI 2.1 或 Request.Content(特别是现在)是否与 .NET 4.03 兼容?在我的项目中没有Request.Content 定义
  • Web API 2.1 应该是,.NET 版本 AFAIK 没有限制。在 .NET 4.0.3 中使用 async-await 需要您使用 Microsoft.Async.Bcl 库。
  • Visual Studio 2010 不支持这个包, 我知道有一天我需要收拾行李搬家,但现在不行.. 我仍然坚持熟悉的2010 年,在桌面应用程序中我还没有达到微软的顶级开发技术,我可以在 web 开发中看到故事是不同的。如果你不使用最新的......好吧一切。您根本无法工作(根本无法工作,但最佳)
  • 嗯,2010 年的 IDE 已经有 6 年历史了,您绝对应该继续使用支持更广泛选项的更新版本。
  • 所以当我很快的时候,移到 2013/15 你是说原始文件只是简单地转换为所需的数据格式?
猜你喜欢
  • 2017-02-14
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 2020-12-07
  • 1970-01-01
相关资源
最近更新 更多