如何解决StatusCode.415, ReasonPhrase: 'Unsupported Media Type'? 415,ReasonPhrase: 'Unsupported Media Type'?

问题描述 投票:0回答:1

如何用HttpClient发布一个文件,不会那么难吧?

我从Windows窗体客户端发布一个文件到ASP.Net Core 2.2网站API(不是WebApi)。

文件可以是任何东西,word、pdf、图片、视频等......文件可以是500MB以内的任何东西,而我的JSON方法不会发送超过25MB的东西

无论我做什么,我一直得到

StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'

我不知道哪里出了问题,我不知道缺了什么。我把范围缩小到这个程度

            string filepath = file;
            string filename = Path.GetFileName(file);

            MultipartFormDataContent content = new MultipartFormDataContent();

            var fileContent = new StreamContent(File.OpenRead(filepath));

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = $"\"{filename}\"" };

            content.Add(fileContent);

            HttpResponseMessage response = await _httpClient.PostAsync(serviceMethod, content);

我读过的所有例子(很多),大多数似乎都是感应JSON,我可以做到这一点。其余的告诉你要读取和寻找什么,但我还是很迷茫,我只是想发一个文件。我已经准备好了服务器的代码。

    [HttpPost]
    public async Task<JsonResult> UploadFile([FromForm]IFormFile result)        

我会继续阅读,但任何帮助将是非常感激的。

好吧,我有点接近了。我更新了我的代码(见上文),现在我的API上的控制器被调用了,但现在是 resultnull

visual-studio winforms asp.net-core
1个回答
0
投票

试着修改你的代码,如图所示。

public async Task<IActionResult> PostFile()
{
        string filepath =file;
        string filename = Path.GetFileName(file);

        MultipartFormDataContent content = new MultipartFormDataContent();

        var fileContent = new StreamContent(System.IO.File.OpenRead(filepath));

        content.Add(fileContent, "result", filename);

        HttpResponseMessage response = await _httpClient.PostAsync(serviceMethod, content);
 }

    [HttpPost]
    public async Task<JsonResult> UploadFile(IFormFile result)        

结果enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.