Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API ASP.NET Core Post Request 415 Unsupported Media Type

I'm new at ASP.NET core and trying to POST a file to a server, but keeps getting 415 Unsupported Media Type error even before hitting any of the code. It does not matter whether the file is PNG, PDF, or even TXT. Is there a setting that I'm missing here? I'm testing it with Postman using POST request and form-data. Thanks in advance for any help I could get.

Postman screenshot

Here's the Web API side:

[Route("api/[controller]")]
[ApiController]
public class ImageUploadController : ControllerBase
{
    public static IWebHostEnvironment _environment;

    public ImageUploadController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    public class FileUploadAPI
    {
        public IFormFile files { get; set; }
    }

    [HttpPost]
    public async Task<string> Post(FileUploadAPI objFile)
    {
        try
        {
            if (objFile.files.Length > 0)
            {
                if (!Directory.Exists(_environment.WebRootPath + "\\Upload\\"))
                {
                    Directory.CreateDirectory(_environment.WebRootPath + "\\Upload\\");
                }
                using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName))
                {
                    objFile.files.CopyTo(fileStream);
                    fileStream.Flush();
                    return "\\Upload\\" + objFile.files.FileName;
                }
            }
            else
            {
                return "Failed";
            }
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }
}
like image 481
msharp Avatar asked Jan 31 '26 22:01

msharp


1 Answers

Add [FromForm] .

    [HttpPost]
    public async Task<string> Post([FromForm]FileUploadAPI objFile)
    {
        // codes
    }
like image 179
Arsalan Valoojerdi Avatar answered Feb 02 '26 15:02

Arsalan Valoojerdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!