簡體   English   中英

從控制台應用程序接收文件時,IFormFile 始終為空

[英]IFormFile is always null when receiving file from console app

我的 WebAPI 方法准備好接受文件作為如下所示的參數:(例如 URI "https://localhost:44397/api/uploadfile"

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

正在使用控制台應用程序將文件發送到此 API 方法,以下是我的代碼:

    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),但它也失敗了(所以這似乎是服務器端的問題,而不是控制台應用程序)。

不知道我在這里做錯了什么。 每當我檢查我的 WebAPI 方法文件參數時,它總是為空。

誰能幫我找到解決方案? 我嘗試搜索博客無濟於事。 我可能在這里做了一些幼稚的事情。

最后我讓它工作。 這一定是微軟的一個錯誤,或者他們可能已經改變了 ApiController 的 .net core 2.1 的工作方式。

我將我的 WebApi 方法更改為以下方法,瞧它起作用了。

注意:刪除了 ApiController 並且它起作用了。 微軟應該記錄這一點。

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

它可能會幫助像我一樣掙扎的人。

這個問題的答案仍然存在,但對於想要保留 [ApiController] 屬性的任何人來說,都有一個解決方法,如此GitHub 線程中所述。

基本上,嘗試像這樣擴展 [FromForm] 屬性......

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

嘗試對您的MultipartFormDataContent顯式內容類型

var contentfile = new StreamContent(fs);
contentfile.Headers.ContentType = MimeMapping.GetMimeMapping(fileName);
content.Add(contentfile, "file", fn);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM