在asp.net中从jQuery调用WCF服务

时间:2013-05-05 09:07:30

标签: wcf jquery

我正在尝试使用asp.net中的jQuery调用WCF服务

WCF服务和asp.net网站属于同一解决方案,但它们运行在不同的端口,如下所示

 WCF - http://127.0.0.1:54443/Service1.svc/
 asp.net - http://127.0.0.1:57484/WebSite2/

以下是WCF功能代码

[WebInvoke(Method = "GET",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]

        public List<string> getCurrentTime()
        {
            List<string> lstrSampleDate = new List<string>();
            lstrSampleDate.Add(DateTime.Now.TimeOfDay.ToString());
            return lstrSampleDate;
        }

以下是jquery代码

 $.ajax({

                 type: "GET",
                 url: "http://127.0.0.1:54443/Service1.svc/getCurrentTime",
                 // crossDomain: true,
                 datatype: "json",
                 success: function (rVal) {
                     //console.log
                     alert(rVal);
                 },
                 error: function (xhr, status) {
                     //console.log
                     alert('Error: ' + xhr.statusText + 'Status: ' + xhr.status);
                 },
                 complete: function (xhr, status) {
                     //console.log
                     alert("The request is completed!");
                 }
             });

当我执行代码时,我得到以下错误,在控制台中打印

> XMLHttpRequest cannot load
> http://127.0.0.1:54443/Service1.svc/getCurrentTime. Origin
> http://127.0.0.1:57484 is not allowed by Access-Control-Allow-Origin.

作为一种解决方法,我确实将以下设置添加到配置文件(网站)

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
</httpProtocol>
</system.webServer>

仍然取得了丰硕的成果。任何人都可以指出我失踪的地方吗?

注意:我用127.0.0.1替换了'localhost' 感谢

1 个答案:

答案 0 :(得分:0)

您可能会发现这篇文章有用:Access-Control-Allow-Origin error sending a jQuery Post to Google API's

  

我解决了Access-Control-Allow-Origin错误修改dataType   dataType参数:'jsonp'并添加一个crossDomain:true