c# - 在 .net 核心 webapi Controller 中接受 byte[]

标签 c# asp.net-core asp.net-core-webapi

您如何在 .net 核心的 WebAPI Controller 中接受字节 []。如下所示:

    [HttpPost]
    public IActionResult Post(byte[] rawData)
    {
        try
        {
            System.Diagnostics.Trace.WriteLine("Total bytes posted: " + rawData?.Length);
            return StatusCode(200);
        }
        catch(Exception ex)
        {
            return StatusCode(500, $"Error. msg: {ex.Message}");
        }
    }

从 fiddler 测试时,我收到 415 Unsupported Media Type 错误。 这在 .net 核心 webapi 中甚至可能吗?我搜索了一段时间,没有.net core 的解决方案。有一些 BinaryMediaTypeFormatter 的示例不适用于 .net 核心 webapi。如果 webapi 无法做到这一点,那么在 .net 核心 Web 应用程序中接受字节数组的最佳解决方案是什么?

我们的旧应用程序是一个 asp.net 表单应用程序。它将调用 Request.BinaryRead() 来获取字节数组并处理数据。我们正在将此应用程序迁移到 .net 核心。

谢谢。

最佳答案

最终创建了一个 InputFormatter 以将发布的数据读取为 byte[] 数组。

public class BinaryInputFormatter : InputFormatter
{
    const string binaryContentType = "application/octet-stream";
    const int bufferLength = 16384;

    public BinaryInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(binaryContentType));
    }

    public async override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        using (MemoryStream ms = new MemoryStream(bufferLength))
        {
            await context.HttpContext.Request.Body.CopyToAsync(ms);
            object result = ms.ToArray();
            return await InputFormatterResult.SuccessAsync(result);
        }
    }

    protected override bool CanReadType(Type type)
    {
        if (type == typeof(byte[]))
            return true;
        else
            return false;
    }
}

在 Startup 类中配置

        services.AddMvc(options =>
        {
            options.InputFormatters.Insert(0, new BinaryInputFormatter());
        });

我的 WebAPI Controller 有以下方法来接收 HTTP 发布的数据(注意,我的默认路由将 Post 作为操作而不是索引。)

    [HttpPost]
    public IActionResult Post([FromBody] byte[] rawData)
    {
        try
        {
            System.Diagnostics.Trace.WriteLine("Total bytes posted: " + rawData?.Length);
            return StatusCode(200);
        }
        catch(Exception ex)
        {
            return StatusCode(500, $"Error. msg: {ex.Message}");
        }
    }

在对 Controller 执行 HTTP Post 后,rawData 参数在字节数组中包含已发布的数据。

关于c# - 在 .net 核心 webapi Controller 中接受 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50918007/

相关文章:

.net - CloudTableClient 与.NET Core 不兼容?

asp.net-web-api - 无法运行 Swagger UI

c# - 将 ZipArchive 与 ASP.NET Core Web Api 结合使用

c# - 根据文件名中的日期过滤目录中的文件

c# - X509Certificate2 访问私钥到安全 token

C# Hashtable Add 与 Indexer - 为什么两者都有?

c# - 合并 pdf 列表并创建新书签 (C#)

c# - Azure消息总线异步检索数据并通过 Controller 操作返回数据

docker - AddOpenIdConnect options.Authority 被代理后面的当前主机覆盖(UseForwardedHeaders)

c# - 使用 FromBody 在 WebAPI 中建模的 JSON 对象和简单类型