IFormFile is always null when receiving file from console app

梦想的初衷 提交于 2019-12-06 11:41:26

问题


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.


回答1:


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.




回答2:


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)
    {
    }
}



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!