如何从javascript调用WCF服务?

时间:2017-06-26 15:36:16

标签: javascript jquery ajax wcf soap

我正在尝试使用jQuery从ajax调用调用WCF服务。 我设法从SOAP-UI和Excel / VBA调用WCF。 我的问题来自发送的OPTIONS请求,后面没有POST:

  • 如果我将网址设置为http://mywcf/service.svc,则会发送OPTIONS并获得400 Bad Request状态,并且不会发送POST请求。在这种情况下,标头中缺少HTTP/1.1(与SOAP-UI标头比较)。
  • 如果我将网址设置为http://mywcf/service.svc HTTP/1.1,则会发送OPTIONS并获得200 OK状态,但不会发送POST请求。在这种情况下,HTTP/1.1似乎被解释为文件名。

有人可以告诉我如何从javascript调用WCF上的POST操作并添加HTTP/1.1标题而不破坏服务URL吗?

以下是我的ajax调用的摘录:

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

<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>

3 个答案:

答案 0 :(得分:1)

添加webHttpBinding端点

    <services>
  <service name="Contract">
    <endpoint address="json" binding="webHttpBinding"  contract="IContract" bindingConfiguration="ActionsHttpBinding" behaviorConfiguration="ActionrestfulBehavior"/>
  </service>

然后从ajax调用端点作为post或get,见下面的例子:

    var data = JSON.stringify({
    param1: val1,
    param2: val2
});
$.ajax({
    url: "http://mywcf/service.svc/json/FunctionName",
    type: "POST",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    processData: true
}).then(function (rsutlt) {

}).fail(function (fail) {
});

答案 1 :(得分:1)

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

要设置请求,请先定义变量。当您调用多个方法并创建不同的js文件来调用WCF服务时,这将非常有用。

<script type="text/javascript">

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

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

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中设置数据来向服务发送请求。

// 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中找不到的对象。

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>

答案 2 :(得分:0)

将以下代码添加到您的global.asax.cs,并从您的网络配置中删除customHeaders。

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }

    }

此外,您还需要删除OPTIONSVerbHandler以启用角色。

 <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>