WCF AJAX 调用无法与Jquery $.ajax一起使用

oalqel3c  于 2023-01-20  发布在  jQuery
关注(0)|答案(2)|浏览(247)

我有以下jQuery(服务名称已更改):

var url = "http://localhost/services/MyService.svc/addentrant";
var stuff = $("#signup-form").serializeArray();

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    data: stuff,
    timeout: 10000,
    success: function (obj) { alert('yay!'); }
});

上面的代码向我本地IIS7.5服务器上Sitefinity托管的WCF服务发出请求,下面是相关的web.config:

<endpointBehaviors>
<behavior name="jsonBehavior">
  <webHttp/>
</behavior>
...
<serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
...
<services>
 <service behaviorConfiguration="DefaultBehavior" name="Services.MyService" >
        <endpoint address="" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" contract="Services.IMyService" bindingConfiguration=""/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 </service>
...

最后,MyService的接口与实现:

[ServiceContract(Name = "MyService", Namespace = "http://myservice.com/services/2010/")]
public interface IMyService
{
    [OperationContract,
    WebInvoke(Method = "POST",
              ResponseFormat = WebMessageFormat.Json,
              BodyStyle = WebMessageBodyStyle.WrappedRequest,
              UriTemplate = "addentrant")]
    void AddEntrant(string firstName);
}
...
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyervice
{
...
    public void AddEntrant(string firstName)
    {
        Entrant entrant = new Entrant()
        {
            FirstName = firstName,
        };
        context.Entrants.InsertOnSubmit(entrant);
        context.SubmitChanges();
    }
}

总之,$. AJAX 调用返回成功,但是Web服务方法没有被调用(我设置了断点)。我打开Fiddler,发现我得到了一个405:方法不被允许。我以前见过这种情况,但只是在我忘记设置方法允许POST请求的时候。我很困惑为什么它现在这样做。
而且,奇怪的是,如果我克隆在Fiddler中捕获的 AJAX 请求,我会得到以下内容:

OPTIONS /services/MyService.svc/addentrant HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://localhost:6339
Access-Control-Request-Method: POST

只有标题,没有请求正文。

fykwrbwg

fykwrbwg1#

如果尝试使用GET而不是POST会发生什么?
尝试清除缓存或在url上附加时间戳-200响应代码可能已被浏览器缓存

8ljdwjyq

8ljdwjyq2#

另一种尝试方法是不要在$.ajax调用中设置contentType,而是使用dataType: "json"

$.ajax({
    type: "POST",
    url: url,
    dataType: "json",
    data: stuff,
    timeout: 10000,
    success: function (obj) { alert('yay!'); }
});

相关问题