【问题标题】:Accepting binary data in asp net controller在 asp 网络控制器中接受二进制数据
【发布时间】:2021-08-26 13:04:53
【问题描述】:

我正在努力绑定在 http 请求正文中发送的二进制数据。

我在 Asp Net core (NetCore 2.1) 中有以下控制器:

    [HttpPost]
    [Consumes("image/png", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
    [Route("test")]
    public IActionResult Test(IFormFile file)
    {
        return Ok(file.Length);
    }

目的是接收字节流并将其绑定到名为“文件”的参数。问题是 IFormFile 变量为空。事实上,通过在控制器中放置断点,Route 可以完美运行,但是一旦我尝试访问“文件”变量,它就会引发空指针异常。

我怀疑它的工作方式。如果我访问 Request 对象,我可以毫无问题地读取数据流。但我认为这不是正确的做法。
示例:

    [HttpPost]
    [Consumes("image/png", "image/bmp", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
    [Route("test")]
    public IActionResult Test(IFormFile binary)
    {
        var x = new System.Drawing.Bitmap(Request.Body);
        x.Save(".\\file.bmp");
        return Ok("Image height: " + x.Height.ToString());
    }

如何在我的控制器中绑定以二进制形式发送的数据?

以下是邮递员发送的请求示例:
postman screenshot
raw request

附:尽管我知道在多部分形式中接收数据会更好,但我很愿意以二进制形式接收数据

【问题讨论】:

  • 如果你想绑定二进制到IFormFile二进制,你可以尝试使用custom model binding
  • @YiyiYou 感谢您的建议,但我确实找到了我想要的东西

标签: c# api asp.net-core controller


【解决方案1】:

刚刚在那里找到了解决方案:https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers?Page=2

我正在寻找一种将原始 Request.Body Stream 绑定到控制器参数的方法,而且非常简单。

我刚刚创建了一个自定义格式化程序,如下所示:

public class RawRequestBodyFormatter : InputFormatter
{
  public RawRequestBodyFormatter()
  {
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/bmp"));
  }


/// <summary>
/// Allow image/bmp and no content type to
/// be processed
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Boolean CanRead(InputFormatterContext context)
{
    if (context == null) throw new ArgumentNullException(nameof(context));

    var contentType = context.HttpContext.Request.ContentType;
    if (string.IsNullOrEmpty(contentType) || contentType == "image/bmp")
        return true;

    return false;
}

/// <summary>
/// Handle bmp images
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
    var request = context.HttpContext.Request;
    var contentType = context.HttpContext.Request.ContentType;

    if (string.IsNullOrEmpty(contentType) || contentType == "image/bmp")
    {
        return await InputFormatterResult.SuccessAsync(request.Body);
    }

    return await InputFormatterResult.FailureAsync();
}

然后将相应的选项添加到我的应用中

services.AddMvc(options =>
            options.InputFormatters.Insert(0, new 
RawRequestBodyFormatter())

现在下面的 Controller 可以正常工作了!

[HttpPost]
[Consumes("image/png", "image/bmp", System.Net.Mime.MediaTypeNames.Application.Pdf, System.Net.Mime.MediaTypeNames.Image.Tiff)]
[Route("test")]
//[JwtAuthenticationAttribute]
public IActionResult Test([FromBody]Stream file)
{
     var x = new System.Drawing.Bitmap(file);
     x.Save(".\\file.bmp");
     return Ok("Image height: " + x.Height.ToString());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多