WebAPI将XML或NULL返回给Firefox(想要JSON)

时间:2014-10-21 20:26:59

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

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

/// <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);
}

...其中“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

这似乎确实是问题所在。

1 个答案:

答案 0 :(得分:0)

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

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