使用纯javasript / html页面调用WCF Web服务使用JSONP解决跨域问题,得到错误消息“方法不允许”,在网上进行了大量搜索,但无法获得有效的解决方案..
架构: WCF 3.5 + JSONP + JQuery
要在WCF 3.5中启用JSONP功能,我添加了MSDN JSONP示例lib文件:
JSONPBehavior.cs
JSONPBindingElement.cs
JSONPBindingExtension.cs
JSONPEncoderFactory.cs
来自http://msdn.microsoft.com/en-us/library/cc716898.aspx的。 关注此帖:http://jasonkelly.net/2009/05/using-jquery-jsonp-for-cross-domain-ajax-with-wcf-services/
IService1.cs:
namespace WcfServiceForConnDatabase
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetData")]
[JSONPBehavior(callback = "method")]
string GetData();
}
}
service.cs:
namespace WcfServiceForConnDatabase
{
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class Service1 : IService1
{
public string GetData()
{
return "Successfully connect with the WCF Web Service";
}
}
}
的web.config:
<?xml version="1.0"?>
<configuration>
<!-- WCF configuration -->
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WcfServiceForConnDatabase.Service1Behavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfServiceForConnDatabase.Service1">
<endpoint address="" behaviorConfiguration="WcfServiceForConnDatabase.Service1Behavior" binding="customBinding" bindingConfiguration ="jsonpBinding" contract="WcfServiceForConnDatabase.IService1"/>
</service>
</services>
<bindings>
<customBinding>
<binding name="jsonpBinding" >
<jsonpMessageEncoding />
<httpTransport manualAddressing="true"/>
</binding>
</customBinding>
</bindings>
<extensions>
<bindingElementExtensions>
<add name="jsonpMessageEncoding" type="WcfServiceForConnDatabase.JsonpBindingExtension, WcfServiceForConnDatabase, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</bindingElementExtensions>
</extensions>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
前端:
$.ajax({
url: "http://192.168.0.23/Service1.svc/GetData",
type: "GET",
jsonpCallback: "TestData",
contentType: "application/json",
dataType: "jsonp",
error: function () {
alert("Error");
},
success: function (data) {
alert("Success");
}
});
}
网络结构如下: LAN中有两台PC;一台用于客户端javascript页面,另一台用于Web服务(192.168.0.23)。
希望有人能给我一些建议!!!感谢大家!答案 0 :(得分:0)
在jQuery AJAX调用(跨域)中使用WCF时必须考虑的事项;
查看此信息以获取更多信息:
Consuming a WCF Service in jQuery via AJAX Call in a different Project (Cross Domain)