visual-studio - 如何解决 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 上的控制器正在被调用,但现在result
是null
解决方案
尝试更改您的代码,如下所示:
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)
推荐阅读
- reactjs - 在故事书中设置时反应本机下拉选择器错误
- ios - 当两个框架包含与 iOS 中的资源相同的图像时,不从一个框架加载图像
- python - Kivy/KivyMD - 按钮没有反应
- airflow - Airflow - 获取报告的后端数据库
- python-3.x - 从 Python 列表中删除引号和白色字符
- android - Android Studio:设置并将选择的微调器值传输到下一个活动
- sql-server - 错误:按表达式分组必须至少包含一列不是外部引用
- elasticsearch - 更新 Elastic Search 中固定文档的分数
- javascript - 在 JavaScript 中的数组输入处过滤数组最小值的问题
- postgresql - 配置:ActiveDirectory、PostgreSQL、GSSAPI