ASPNetCore API IFormFile返回“无效输入”

时间:2018-09-26 17:17:18

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

我有一个api,我正在尝试上传图片。我试过用招摇和邮递员。

我回来的就是

{
    "": [
        "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也会引发相同的错误。 我的代码中没有其他错误,调试也无济于事(试图在控制器中设置断点,但显然它们没有采用或不应该这样做,仍在这里学习)。

任何帮助将不胜感激。谢谢!

enter image description here

进行了干净的测试,问题似乎出在[ApiController]中。知道为什么/如何解决它?

1 个答案:

答案 0 :(得分:2)

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

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