Reputation: 932
I have an api and i'm trying to upload an image. I tried using swagger & postman.
All i'm getting back is
{
"": [
"The input was not valid."
]
}
This is how my code looks like ->
Controller -
[HttpPost("images")]
public async Task<IActionResult> UploadImage(IFormFile file)
{
return await _imageHandler.UploadImage(file);
}
Image Handler -
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);
}
}
And finally image writer
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;
}
}
I was following this tutorial -> https://www.codeproject.com/Articles/1256591/Upload-Image-to-NET-Core-2-1-API
I've already modified Swagger in the project to be able to upload files, but even swagger throws the same error. I got no other errors in my code & debugging does nothing (trying to set breakpoints in my controller, but apparently they dont take or they aren't supposed to, still learning here).
Any help will be appreciated. Thanks!
Did a clean test and the problem seems to be in [ApiController]
. Any idea why/how i can fix it?
Upvotes: 1
Views: 994
Reputation: 932
Found my problem and found my fix. After finding that my problem was [ApiController] i stumbled upon another stackoverflow problem related to this.
This fixed my problem. Modifyingservices.AddMvc()
to -> services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Upvotes: 3