首页 > 解决方案 > 如何解决 StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'?

问题描述

您如何使用 HttpClient 发布文件?不会那么难吧?

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

该文件可以是任何东西,文字,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-studiowinformsasp.net-core

解决方案


尝试更改您的代码,如下所示:

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)        

结果 在此处输入图像描述


推荐阅读