【问题标题】:WebAPI returning either XML or NULL, to Firefox (want JSON)WebAPI 向 Firefox 返回 XML 或 NULL(需要 JSON)
【发布时间】:2014-10-21 20:26:58
【问题描述】:

我有一个返回对象的 ASP.NET WebAPI 网络服务:

/// <summary>
/// upload a single file, as a new attachment, or overwrite an existing attachment
/// </summary>
/// <returns>new attachment, if created</returns>
[HttpPost, ActionName("uploadAttachment")]
public async Task<HttpResponseMessage> uploadAttachment(string jobid)
{
    if (!Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

    await Request.Content.ReadAsMultipartAsync(provider);

    var attachment = [...];

    return Request.CreateResponse(HttpStatusCode.OK, attachment);
}

...其中“附件”是一个 POCO 对象,其中包含我需要返回的信息。

我使用 XMLHttpRequest 调用它:

AttachmentService.prototype.uploadAttachment = function(jobid, name, imageData, notes, callback)
{
    var url = [...];

    var formData = new FormData();
    formData.append('name', name);
    formData.append('notes', notes);
    formData.append('imageData', imageData);

    var xhr = new XMLHttpRequest();
    xhr.addEventListener('load', function(e)
    {
        var response = {};

        if (e.target.status == 200)
        {
            response.success = true;
            response.data = JSON.parse(e.target.response);
        }
        else
        {
            response.success = false;
            response.message = e.target.message;
            response.data = null;
        }
        callback(response);
    });

    xhr.open('POST', url, true);

    //xhr.responseType = 'json';

    xhr.setRequestHeader("authenticationToken", CORE.getAuthToken());
    xhr.send(formData);
};

这在 IE11 和 Chrome 中运行良好。在 Firefox 33 中,e.target.response 是 XML,而不是 JSON。

我浏览了一些网络,并看到了一些关于客户端和服务器端的建议。看起来最简单的方法是指定 xhr.responseType,如上面代码中的注释所示。

这行不通。

当我设置“xhr.responseType = 'json'”时,e.target.response 返回 null。

想法?

其他信息

尝试查看 Fiddler 中的请求标头。

在 Chrome 中:

 Accept: application/json, text/javascript, */*; q=0.01

在 IE11 中:

 Accept: */*

在 Firefox 中:

 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

看来这确实是个问题。

【问题讨论】:

    标签: javascript asp.net json firefox asp.net-web-api


    【解决方案1】:

    您可以将标头设置为application/json

    x.setRequestHeader('Content-type','application/json; charset=utf-8');
    

    【讨论】:

    • 如果我这样做,当我从 Chrome 加载页面时,我会收到 HTTP 415,当我从 Firefox 加载页面时,我会收到内部服务器错误。让我感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多