我有以下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
只是标题,没有请求机构可以说。
答案 0 :(得分:0)
如果您尝试使用GET而不是POST,会发生什么?
尝试清除缓存或在网址上附加时间戳 - 浏览器可能已缓存200响应代码
答案 1 :(得分:0)
要尝试的另一件事是不在contentType
来电中设置$.ajax
,而是使用dataType: "json"
。
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: stuff,
timeout: 10000,
success: function (obj) { alert('yay!'); }
});