ASPNetCore API IFormFile 返回 "invalid input"

ASPNetCore API IFormFile returning "invalid input"

我有一个 api,我正在尝试上传图片。我尝试使用 swagger 和 postman。

我要回来的只是

{
    "": [
        "The input was not valid."
    ]
}

这是我的代码的样子 ->

控制器-

    [HttpPost("images")]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        return await _imageHandler.UploadImage(file);
    }

图像处理程序 -

public interface IImageHandler
{
    Task<IActionResult> UploadImage(IFormFile file);
}

public class ImageHandler : IImageHandler
{
    private readonly IImageWriter _imageWriter;
    public ImageHandler(IImageWriter imageWriter)
    {
        _imageWriter = imageWriter;
    }

    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        var result = await _imageWriter.UploadImage(file);
        return new ObjectResult(result);
    }
}

最后是图片作者

public class WriterHelper
{
    public enum ImageFormat
    {
        bmp,
        jpeg,
        gif,
        tiff,
        png,
        unknown
    }

    public static ImageFormat GetImageFormat(byte[] bytes)
    {
        var bmp = Encoding.ASCII.GetBytes("BM");     // BMP
        var gif = Encoding.ASCII.GetBytes("GIF");    // GIF
        var png = new byte[] { 137, 80, 78, 71 };              // PNG
        var tiff = new byte[] { 73, 73, 42 };                  // TIFF
        var tiff2 = new byte[] { 77, 77, 42 };                 // TIFF
        var jpeg = new byte[] { 255, 216, 255, 224 };          // jpeg
        var jpeg2 = new byte[] { 255, 216, 255, 225 };         // jpeg canon

        if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
            return ImageFormat.bmp;

        if (gif.SequenceEqual(bytes.Take(gif.Length)))
            return ImageFormat.gif;

        if (png.SequenceEqual(bytes.Take(png.Length)))
            return ImageFormat.png;

        if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
            return ImageFormat.tiff;

        if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
            return ImageFormat.tiff;

        if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
            return ImageFormat.jpeg;

        if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
            return ImageFormat.jpeg;

        return ImageFormat.unknown;
    }
}

我正在学习本教程 -> https://www.codeproject.com/Articles/1256591/Upload-Image-to-NET-Core-2-1-API

我已经在项目中修改了Swagger可以上传文件,但是即使是swagger也会报同样的错误。 我的代码中没有其他错误并且调试没有任何作用(尝试在我的控制器中设置断点,但显然他们不接受或不应该接受,仍在此处学习)。

如有任何帮助,我们将不胜感激。谢谢!

进行了彻底的测试,问题似乎出在 [ApiController]。有什么想法 why/how 我可以解决它吗?

找到我的问题并找到我的解决方法。 在发现我的问题是 [ApiController] 之后,我偶然发现了另一个与此相关的 Whosebug 问题。

这解决了我的问题。修改services.AddMvc() 为 -> services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);