如何从javascript调用WCF服务? [英] How to call a WCF service from javascript?

查看:33
本文介绍了如何从javascript调用WCF服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery 从 ajax 调用中调用 WCF 服务.我设法从 SOAP-UI 和 Excel/VBA 调用 WCF.我的问题来自发送的 OPTIONS 请求并且没有 POST 跟随:

I'm trying to call a WCF service from an ajax call with jQuery. I manage to call the WCF from SOAP-UI and from Excel/VBA. My problem comes from the OPTIONS request that's sent and no POST follows:

  • 如果我将 URL 设置为 http://mywcf/service.svc,则会发送 OPTIONS 并且我会收到 400 Bad Request 状态并且不会发送 POST 请求.在这种情况下,标头中缺少 HTTP/1.1(与 SOAP-UI 标头相比).
  • 如果我将 URL 设置为 http://mywcf/service.svc HTTP/1.1,则发送 OPTIONS 并且我得到 200 OK 状态但 POST 请求不是发送.在这种情况下,HTTP/1.1 似乎被解释为文件名.
  • if I set URL to http://mywcf/service.svc, OPTIONS is sent and I get a 400 Bad Request status and POST request is not sent. In this case, there's missing HTTP/1.1 in header (comparing with SOAP-UI headers).
  • if I set URL to http://mywcf/service.svc HTTP/1.1, OPTIONS is sent and I get a 200 OK status but POST request is not sent. In this case, HTTP/1.1 seems to be interpreted as a filename.

谁能告诉我如何从 javascript 调用 WCF 上的 POST 操作并添加 HTTP/1.1 标头而不破坏服务 URL?

Can someone tell me how to call a POST action on a WCF from javascript and to add HTTP/1.1 header without corrupting service URL?

这是我的 ajax 调用的摘录:

Here is a extract from my ajax call:

var soapData = ''
        +'<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:mic="http://microsoft.wcf.documentation">'
        +'    <soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsrm="http://docs.oasis-open.org/ws-rx/wsrm/200702">'
        +'        <wsrm:Sequence>'
        +'            <wsrm:Identifier>s:Sender a:ActionNotSupported</wsrm:Identifier>'
        +'            <wsrm:MessageNumber>1</wsrm:MessageNumber>'
        +'        </wsrm:Sequence>'
        +'        <wsa:Action>http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence</wsa:Action>'
        +'        <wsa:ReplyTo>'
        +'            <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>'
        +'        </wsa:ReplyTo>'
        +'        <wsa:MessageID>uuid:'+ MsgUid +'</wsa:MessageID>'
        +'        <wsa:To>'+ Url +'</wsa:To>'
        +'    </soap:Header>'
        +'    <soap:Body xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm">'
        +'        <wsrm:CreateSequence>'
        +'            <wsrm:AcksTo xmlns:wsa="http://www.w3.org/2005/08/addressing">'
        +'                <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>'
        +'            </wsrm:AcksTo>'
        +'            <wsrm:Offer>'
        +'                <wsrm:Identifier>urn:soapui:'+ SeqUid +'</wsrm:Identifier>'
        +'            </wsrm:Offer>'
        +'        </wsrm:CreateSequence>'
        +'    </soap:Body>'
        +'</soap:Envelope>';

$.ajax({
    type: 'POST',
    url: 'http://mywcf/service.svc', // with or without +' HTTP/1.1'
    data: soapData,
    contentType: 'application/soap+xml;charset=UTF-8',
    dataType: 'xml'
});

我的 WCF web.config 中的值:

Values in my WCF web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="POST, OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

推荐答案

要使用 jQuery 使用 Web 服务,即调用 WCF 服务,您可以使用 jQuery.ajax() 或 jQuery.getJSON().在本文中,我使用了 jQuery.ajax() 方法.

To consume a web service using jQuery, that is to make a call to the WCF service, you either use jQuery.ajax() or jQuery.getJSON(). In this article I used the jQuery.ajax()method.

要设置请求,首先定义一个变量.当您调用多个方法并创建不同的 js 文件来调用 WCF 服务时,这会很有帮助.

To set the request, first define a variable. This will be helpful when you are calling multiple methods and creating a different js file to call the WCF service.

<script type="text/javascript">

    var Type;
    var Url;
    var Data;
    var ContentType;
    var DataType;
    var ProcessData;

以下函数初始化上面定义的变量以调用服务.

The following function initializes variables which are defined above to make a call to the service.

function WCFJSON() {
    var userid = "1";
    Type = "POST";
    Url = "Service.svc/GetUser";
    Data = '{"Id": "' + userid + '"}';
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; varProcessData = true; 
    CallService();
}

CallService 函数通过在 $.ajax 中设置数据向服务发送请求.

The CallService function sends requests to the service by setting data in $.ajax.

// Function to call WCF  Service       
function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function(msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result) {
    alert('Service call failed: ' + result.status + '' + result.statusText);
    Type = null;
    varUrl = null;
    Data = null; 
    ContentType = null;
    DataType = null;
    ProcessData = null;
}

注意:以下代码检查 result.GetUserResult 语句,因此您的结果对象获取您的服务方法名称 + Result 的属性.否则,它会给出类似在 Javascript 中找不到对象的错误.

Note: The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.

function ServiceSucceeded(result) {
    if (DataType == "json") {
        resultObject = result.GetUserResult;

        for (i = 0; i < resultObject.length; i++) {
            alert(resultObject[i]);
        }

    }

}

function ServiceFailed(xhr) {
    alert(xhr.responseText);

    if (xhr.responseText) {
        var err = xhr.responseText;
        if (err)
            error(err);
        else
            error({ Message: "Unknown server error." })
    }

    return;
}

$(document).ready(
    function() {
        WCFJSON();
    }
);
</script>

这篇关于如何从javascript调用WCF服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆