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

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

问题描述

我已经准备好接受文件作为参数的 WebAPI 方法,如下所示:(例如 URIhttps://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)
    {
    }
}

我正在使用控制台应用程序将文件发送到此 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;
        }
    }

我还检查了其他客户端(例如 Postman),但它也失败了(所以这似乎是服务器端的问题,而不是控制台应用程序).

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 blogs to no avail. I may be doing something naive here.

推荐答案

我终于让它工作了.这一定是微软的一个错误,否则他们可能已经改变了 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 并且它起作用了.微软应该记录这一点.

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 始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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