我试图消耗WCF服务,使用jQuery从本地主机到服务器,但弟妹“405不允许的方法”。WCF jQuery的Ajax的跨域策略 - “不允许的方法”
这是我使用的配置:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="jsonp" crossDomainScriptAccessEnabled="true" />
<binding name="jsonpSsl" crossDomainScriptAccessEnabled="true">
<security mode="Transport" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="MyBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyBehavior"
name="MyWs.Service1">
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="jsonp" contract="MyWs.IService1"
behaviorConfiguration="MyBehavior"/>
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="jsonpSsl" contract="MyWs.IService1"
behaviorConfiguration="MyBehavior"/>
</service>
</services>
jQuery函数:
$.ajax({
type: "POST",
url: "http://XXX.XXX.XXX.XXX/wcf/Service1.svc/GetData",
data: '{"value":"2340"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
function OnSuccessCall(response) {
alert(response);
}
function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
的WCF接口:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
方法实现:
public string GetData(int value)
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string json = oSerializer.Serialize(string.Format("You entered: {0}", value));
return json;
}
任何想法如何解决它?
谢谢!
给一个尝试: - 数据类型: “JSONP”,跨域:在$真.ajax({...并为服务和端点行为给出不同的名称'作为一种良好的做法。即使您不需要使用JavaScriptSerializer,如果y你是最新的框架,只是返回字符串应该足够好。 –