【问题标题】:Why does my accept header keep getting changed from application/json to */*为什么我的接受标头不断从 application/json 更改为 */*
【发布时间】:2013-05-16 20:06:50
【问题描述】:

我正在尝试向 WebAPI 服务发送一个 ajax 请求,其接受标头为“application/json”

当我在服务中设置断点时,我看到接受标头以“/”的形式出现。这对我来说行不通,因为我们的代码会检查我们的“已知”媒体类型,如果找不到则拒绝请求。

这是当前状态的 ajax 请求:

$.ajax({
        url: requestUrl,
        type: 'GET',
        accept: {
            json: 'application/json'
        },
        success: function(response, status, xhr) {
            displayUsers(response);
        },
        error: function(xhr, status, exception) {
            alert(exception);
        }
    });

我已经在 IE、Chrome 和 Firefox 中尝试过。全都一样。我正在使用 cors。

【问题讨论】:

  • 你试过在ajax请求中指定dataType: json吗?
  • 我确实尝试过。结果相同

标签: ajax asp.net-web-api http-headers cross-domain


【解决方案1】:

当您发出跨域请求时,您的响应(或 OPTIONS 响应,如果是预先发送的 CORS)是否包含 Access-Control-Allow-Headers: accept 允许接受标头?我的猜测是你没有,浏览器切换到发送*/*的默认行为。

【讨论】:

  • 确实如此。但与此同时,我的印象是,只有在标题存在时才会执行限制。
【解决方案2】:

我仍然不清楚真正的问题是什么,但我能够通过设置标头集合而不是像通常那样设置接受标头来解决它:

$.ajax({
        url: requestUrl,
        type: 'GET',
        headers: {
         'Accept' : 'application/json'
        },
        success: function(response, status, xhr) {
            displayUsers(response);
        },
        error: function(xhr, status, exception) {
            alert(exception);
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-12
    • 2012-07-11
    • 2016-03-09
    • 2019-06-28
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多