如何解决 StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'? [英] How to resolve StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'?

查看:182
本文介绍了如何解决 StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you post a file with HttpClient? It can't be that hard, can it?

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

I am posting a file from a Windows forms client to an ASP.Net Core 2.2 website API (not WebApi)

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

The file could be anything, word, pdf, image, video etc... The file could be anything up to 500MB and my JSON methods won't send anything above 25MB

无论我做什么我都会得到

No matter what I do I keep getting

StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'

我不知道出了什么问题我不知道缺少什么.我已经把范围缩小到这个

I can't work out what's gong wrong I have no idea what's missing. I've narrowed it down to this

            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,我可以毫不费力地做到这一点.其余的告诉您要阅读和查找的内容,但我仍然迷路了,我只想发布一个文件.我准备好了服务器代码.

All the examples I've read (loads of them), most seem to be sensing JSON and I can do that in spades. The rest tell you what to read and look for but I'm still lost I just want to post a file. I have the server code ready to go.

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

我会继续阅读,但任何帮助将不胜感激.

I'll keep reading but any help would be much appreciated.

好的,我靠近了一点.我已经更新了我的代码(见上文),现在我的 API 上的控制器正在被调用,但现在 resultnull

Ok, I got a bit closer. I've updated my code (see above) and now the controller on my API is getting invoked but now result is null

推荐答案

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

Try to change your code as shown:

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)        

结果

这篇关于如何解决 StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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