在.net核心Webapi控制器中接受byte []

vjg*_*jgn 2 c# asp.net-core asp.net-core-webapi

您如何在.net核心的WebAPI控制器中接受byte []。如下所示:

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

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

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

谢谢。

vjg*_*jgn 7

最后创建了一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在启动类中对此进行了配置

        services.AddMvc(options =>
        {
            options.InputFormatters.Insert(0, new BinaryInputFormatter());
        });
Run Code Online (Sandbox Code Playgroud)

我的WebAPI控制器具有以下方法来接收HTTP发布的数据(请注意,我的默认路由将Post作为操作而不是Index。)

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

对控制器执行HTTP发布后,rawData参数将发布的数据存储在字节数组中。