c# - WebClient.UploadFile to ASP.NET MVC hosted in IIS 7 produces HTTP 415: Unsupported media type error
问题描述
I'm migrating an old ASP.NET application's file upload functionality to a somewhat less old ASP.NET MVC Web API application.
The client send a file like this:
WebClient webClient = ...;
webClient.UploadFile(toUri, fromPath);
The old app hosted in IIS 7, received the upload like this, and works fine (in a file named UploadLog.aspx):
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>
<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e)
{
foreach(string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("~/UploadedLogs") + "/" + file.FileName);
}
}
</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
The new one also hosted in IIS (in a file called ClientLogController.cs):
[Route("clientlogs")]
[Route("uploadlogs.aspx")]
[HttpPost]
public async Task<IHttpActionResult> UploadClientLog(HttpPostedFileBase postedFile)
{
if (postedFile == null || postedFile.ContentLength == 0)
return BadRequest();
_clientLogUploadCommandHandler.HandleClientLogUpload(postedFile);
return Ok();
}
However, the upload to the new endpoint produces an HTTP 415, Unsupported media type error.
Any ideas how to resolve the issue?
解决方案
我设法通过更改 API 方法的签名来解决它。新的看起来像这样,其他一切都没有改变:
[HttpPost]
[Route("clientlogs")]
[Route("uploadlogs.aspx")]
public async Task<IHttpActionResult> UploadClientLog()
{
var file = HttpContext.Current.Request.Files.Count > 0
? HttpContext.Current.Request.Files[0] : null;
if (file == null && file.ContentLength == 0)
return BadRequest();
_clientLogUploadCommandHandler.HandleClientLogUpload(file);
return Ok();
}
推荐阅读
- android - 应用因易受 Intent 重定向而被拒绝
- ssrs-2012 - 将目标窗口/选项卡添加到 Tablix 操作 URL
- python - LSTM 模型精度上限,我无法提高它
- google-app-engine - 使用可变项目名称在 App Engine 上设置无服务器 VPC 访问
- ios - 仅从其中文本的末尾启用编辑 TextField
- r - 根据因子对重叠时间间隔进行分类
- java - Spring Security 每次都显示登录
- mongodb - MongoDB nReturned in executionStats
- python - 查找具有与 id 匹配的最近时间戳的行,并添加具有值的行
- python - 我怎样才能用python得到这个输出?熊猫有用吗?