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 blog but to no avail. I may be doing something naive here. Any help greatly appreciated.
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.
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)
{
}
}
try explicit content type to your MultipartFormDataContent
var contentfile = new StreamContent(fs);
contentfile.Headers.ContentType = MimeMapping.GetMimeMapping(fileName);
content.Add(contentfile, "file", fn);
来源:https://stackoverflow.com/questions/52294830/iformfile-is-always-null-when-receiving-file-from-console-app