【问题标题】:Cross-domain calling a WCF Service跨域调用 WCF 服务
【发布时间】:2011-10-05 22:05:45
【问题描述】:

我有一个 WCF 服务,这是我要调用的方法:

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    double?[] GetPoints(string tourname);

我通过 WCF 测试客户端检查过,它工作正常

所以我需要从 html 页面调用这个方法。它应该可以在跨域的其他计算机上工作。

我用 jQuery 1-6-2.min.js 写了一些东西:

var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;

function CallService() {
        alert("CallService");
                $.ajax({
                    type          : varType, //GET or POST or PUT or DELETE verb
                    url           : varUrl, // Location of the service
                    data          : varData, //Data sent to server
                    contentType   : varContentType, // content type sent to server
                    dataType      : varDataType, //Expected data format from server
                    processdata   : varProcessData, //True or False
                    success       : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }

function Start() {
    varType = "POST";
    varUrl = "http://localhost:1592/TourService.svc/GetPoints";
    varData = '{"tourname ":"customname"}';
    varContentType = "application/json; charset=utf-8";
    varDataType = "json";
    varProcessData = true; 
    CallService();
}

function ServiceSucceeded(result) {
    alert("ServiceSucceeded");
    alert(result);
}

function ServiceFailed(result) {
    alert('Service call failed: ' + result.status + ' ' + result.statusText);
    varType = null;
    varUrl = null;
    varData = null;
    varContentType = null;
    varDataType = null;
    varProcessData = null;
}

但是调用 ServiceFailed 函数时显示消息“服务调用失败 0 错误”

如何跨域调用WCF服务?(是否使用jQuery)

谢谢

【问题讨论】:

  • 为什么你认为跨域调用是个问题?并且请更好地分析错误发生在哪里。消息“0 错误”只是表明原始错误消息没有正确转发到 jQuery 错误回调。

标签: javascript jquery wcf web-services cross-domain


【解决方案1】:

基本上你需要使用 jSONP 而不是 jSON:

Using jQuery & JSONP for cross-domain AJAX with WCF services

我会尽快提供一个摘要,以防此链接消失。

另请参阅jQuery documentation,了解有关如何使用 jSONP、jQuery 和 AJAX 的更多信息

【讨论】:

    【解决方案2】:

    .net framework 4 for wcf 现在内置了 json 回调,

    我认为从 jquery1.5 开始,他们添加了以下选项,crossDomain,尝试以下代码

    $.ajax({
        type: "POST",
        dataType: "html",
        crossDomain: true,
        url: "http://www.domain.com/page.aspx",
        error: function() {
            alert("error");
        },
        success: function(msg){
            alert(msg );
        }
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    相关资源
    最近更新 更多