WebClient.UploadFile到IIS 7中托管的ASP.NET MVC会产生HTTP 415:不支持的媒体类型错误

问题描述

我正在将旧的ASP.NET应用程序的文件上载功能迁移到不太旧的ASP.NET MVC Web API应用程序中。

客户端发送如下文件

WebClient webClient = ...;
webClient.UploadFile(toUri,fromPath);

由IIS 7托管的旧应用收到了这样的上载,并且工作正常(在名为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>

新的托管在IIS中(名为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();
}

但是,上传到新端点会产生HTTP 415,不支持媒体类型错误

任何想法如何解决该问题?

解决方法

我设法通过更改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();
}