415(不支持的媒体类型)错误

415 (Unsupported Media Type) Error

在我的 MVC 项目中,我有一个 POST 使用 XmlHttpRequest 对 Web API 的请求。

我以 JSON 格式发送文档路由数组,并希望从服务器获取 Zip 文件 (ArrayBuffer)。

self.zipDocs = function (docs, callback) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {//Call a function when the state changes.
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseBody);
        }
    }
    xhr.open("POST", '../API/documents/zip', true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.responseType = "arraybuffer";
    console.log(docs);
    xhr.send(docs);

    var arraybuffer = xhr.response;
    var blob = new Blob([arraybuffer], { type: "application/zip" });
    saveAs(blob, "example.zip");
}

还有我在 Web 上的 ZipDocs 功能API(使用 DotNetZip 库):

[HttpPost]
    [Route("documents/zip")]
    public HttpResponseMessage ZipDocs([FromBody] string[] docs)
    {

    using (var zipFile = new ZipFile())
    {
        zipFile.AddFiles(docs, false, "");
        return ZipContentResult(zipFile);
    }
}

protected HttpResponseMessage ZipContentResult(ZipFile zipFile)
{
    // inspired from 
    var pushStreamContent = new PushStreamContent((stream, content, context) =>
    {
       zipFile.Save(stream);
        stream.Close(); // After save we close the stream to signal that we are done writing.
    }, "application/zip");

    return new HttpResponseMessage(HttpStatusCode.OK) { Content = pushStreamContent };
}

但是我从服务器得到的响应是:

POST http://localhost:1234/MyProject/API/documents/zip 415 (Unsupported Media Type)

为什么会发生这种情况,我该如何解决?

基于this post

你可能想试试

xhr.setRequestHeader("Accept", "application/json");

并且您的代码在

上缺少一个分号
xhr.setRequestHeader("Content-type", "application/json")

感谢 @David Duponchel I used the jquery.binarytransport.js 库,我将数据作为 JSON 发送到 API,并以二进制形式返回 Zip 文件。

这是我的 JavaScript ZipDocs 函数:

self.zipDocs = function (docs, callback) {
    $.ajax({
        url: "../API/documents/zip",
        type: "POST",
        contentType: "application/json",
        dataType: "binary",
        data: docs,
        processData: false,
        success: function (blob) {
            saveAs(blob, "ZippedDocuments.zip");
            callback("Success");
        },
        error: function (data) {
            callback("Error");
        }
    });
}

API 的代码保持不变。

效果很好。