首页 > 解决方案 > 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?

标签: c#asp.netasp.net-mvcfile-uploadwebclient

解决方案


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

推荐阅读