Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IFormFile is always null when receiving file from console app

I have my WebAPI method ready to accept file as parameter shown below: (e.g. URI "https://localhost:44397/api/uploadfile"

 [Route("api/[controller]")]
 [ApiController]
 public class UploadFileController : ControllerBase
 {
    [HttpPost]
    public async Task<IActionResult> Post([FromForm] IFormFile file)
    {
    }
}

Am using console app to send file to this API method, below is my code:

    public static void Send(string fileName)
    {
        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            client.BaseAddress = new Uri("https://localhost:44397");
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var index = fileName.LastIndexOf(@"\");
            var fn = fileName.Substring(index + 1);
            fs.Position = 0;

            var contentfile = new StreamContent(fs);
            content.Add(contentfile, "file", fn);
            var result = client.PostAsync("/api/uploadfile", content).Result;
        }
    }

I also checked with other clients (e.g. Postman) and it failed there too (so it seems like an issue in the server-side, rather than the console app).

Not sure what am I doing wrong here. Whenever I check my WebAPI method file parameter is always null.

Can anyone help me finding solution to this? I tried searching blogs to no avail. I may be doing something naive here.

like image 857
Joshua I Avatar asked Mar 05 '23 10:03

Joshua I


2 Answers

Finally I made it Working. It must be a bug in microsoft or they may have change the way things works from .net core 2.1 for ApiController.

I changed my WebApi method to the following and voila it worked.

Note: removed ApiController and it worked. Microsoft should document this.

[Route("api/[controller]")]
public class OCRController : ControllerBase
 {
    [HttpPost]
    public async Task<IActionResult> Post([FromForm] IFormFile file)
    {
    }
}

It may help someone who is struggling like me.

like image 67
Joshua I Avatar answered Mar 18 '23 05:03

Joshua I


The answer to this question still stands but for anyone who wants to retain the [ApiController] attribute there is a workaround as described in this GitHub thread.

Basically, try to expand the [FromForm] attribute like so...

[Route("api/[controller]")]
public class OCRController : ControllerBase
 {
    [HttpPost]
    public async Task<IActionResult> Post([FromForm(Name = "file")] IFormFile file)
    {
    }
}
like image 43
Robert Avatar answered Mar 18 '23 03:03

Robert