【问题标题】:c# ajax post 400 bad request firefox onlyc# ajax post 400 bad request only firefox
【发布时间】:2013-06-03 10:19:31
【问题描述】:

我正在尝试使用 C# 后端编写一个 ajax 应用程序。对于 ajax 调用,我使用的是 jquery。它适用于 IE 和 Google Chrome,但当我尝试使用 Firefox 打开它时,它会发出 400 错误请求。这是前端代码

$.ajax({
        url: "http://localhost:25028/Service.svc/Fun",
        type: "POST",
        dataType: "json",
        timeout: 10000,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({input: 'input'}),
        crossDomain: true,
        success: function (input) {
            var data = JSON.parse(input);
            alert(data.data);
        },
        error: function (input, textstatus, errorThrown) {
            alert(textstatus);
        }
    });

如果相关,我将在 web.config 中使用以下绑定。

    <behavior name="EndpBehavior">
      <webHttp />
    </behavior>


  <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" contract="Service" behaviorConfiguration="EndpBehavior"/>
  </service>

函数定义如下

[OperationContract]
[WebInvoke(Method = "*", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string Fun( string input )
{
    return new JavaScriptSerializer().Serialize(new { data = "this is data" });
}

}

我不明白错误是什么。

提前致谢。

【问题讨论】:

  • 使用 fiddler 或 wireshark 找出区别。
  • 尝试清除cache:false
  • 如果你打开 Firebug,它会显示什么作为请求?
  • Firebug 告诉 400 bad request 当我点击它时,它显示以下消息 Accept text/html,application/xhtml+xml,application/xml;q=0.9,/ ;q=0.8 Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Access-Control-Request-He... content-type Access-Control-Request-Me... POST Cache-Control no -cache Connection keep-alive Host localhost:25028 Origin localhost:25121 Pragma no-cache User-Agent Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
  • 我只是想让您检查一下它在“请求”部分下具体显示的内容 - 我的意思是它是否显示了“数据”中的任何内容?

标签: c# jquery ajax wcf firefox


【解决方案1】:

尝试使用提琴手。 http://fiddler2.com。也使用 BodyStyle = WebMessageBodyStyle.Bare 和 Method = "POST"

【讨论】:

    【解决方案2】:

    在返回 Json 之前,您能否尝试在服务实现中添加以下行:

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "x-requested-with");
    

    在此之后,清除 Firefox 会话/cookie(或者更好的是,在“私人浏览模式”下打开 FF) - 并再次点击 url。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2019-10-22
      • 1970-01-01
      • 2017-11-30
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多