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

415 (Unsupported Media Type) Error

本文关键字:类型 错误 媒体 不支持      更新时间:2023-09-26

在我的MVC项目中,我使用XmlHttpRequest向Web API发出POST请求。

我以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");
}

我在WebAPI上的ZipDocs函数(使用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 http://stackoverflow.com/a/16171977/92756
    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)

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

基于此后

你可能想试试

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

您的代码在上缺少分号

xhr.setRequestHeader("Content-type", "application/json")

感谢@David Duponchel,我使用了jquery.binarytransport.js库,将数据以JSON形式发送到API,并以Binary形式返回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的代码保持不变。

这非常有效。