从控制台应用程序接收文件时,IFormFile始终为null [英] IFormFile is always null when receiving file from console app

查看:890
本文介绍了从控制台应用程序接收文件时,IFormFile始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经准备好WebApi方法来接受文件,如下所示:
(例如uri https :// localhost:44397 / api / uploadfile

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使用控制台应用程序将文件发送到此api方法,下面是我的代码:

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).

不知道我在这里做错了什么。每当我检查WebApi方法文件参数始终为空时。

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.

推荐答案

最后,我使它工作了。它一定是Microsoft中的错误,否则它们可能会从ApiController的.net core 2.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.

我将WebApi方法更改为以下内容,并对此进行了说明

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

注意:删除了ApiController,它起作用了。 Microsoft应该对此进行记录。

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.

这篇关于从控制台应用程序接收文件时,IFormFile始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆