user6791921
user6791921

Reputation:

How to use WCF method with jQuery

I am testing my first WCF Service. It has only one method which equals two values given as parameters and returns the result.

It works fine when I use the Test Client provided by Visual Studio, but when I through to develop my own JS client using jQuery, I don´t know how to read data or how to call this method to obtain and show in an alert.

Here is the code:

ImiServicio.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace primerwcf
{

    [ServiceContract]
    public interface ImiServicio
    {
        [OperationContract]
        int getSuma(int numero1, int numero2);
    }
}

miServicio.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace primerwcf
{

    public class miServicio : ImiServicio
    {
        public int getSuma(int numero1, int numero2)
        {
            return numero1+numero2;
        }
    }
}

webconfig

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1" />
        <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
    </system.webServer>
</configuration>

Javascript/Jquery code

$("#b1").click(function()
{
    $.ajax(
    {

         type: "GET",
         url:"http://localhost:50664/miServicio.svc",
         data:{

             numero1:2,
             numero2:6
         },
         dataType: "xml" ,
         success:function(response)
         {
             alert("ok "+response);

         },
         error:function(){

             alert("error");
         }


    });

});

When I simply show

alert(response);

it retuns an object XMLDocument

But when I try to use

$.parseXML(response);

It returns null.

I changed dataType to "text" in the ajax() method but I only obtain the HTML code that would be shown in the browser when I paste the address.

I tried to call the method this way, too:

response.getSumarResult

but it returns undefined.

I looked into these sources, among others:

https://www.codeproject.com/Questions/544312/HowplustoplusreadplusXMLplusFileplusinplusaplusWCF

http://www.developerin.net/a/62-Code-Snippets/49-Calling-WCF-services-using-Jquery

Since most of the tutorials consulted are old, I don´t know if I have to config the webConfig file like some of this sites suggest, given that it seems I obtain the data successfully from the service.

Upvotes: 1

Views: 75

Answers (1)

user6791921
user6791921

Reputation:

After many tests and efforts, I managed to solve it. I will post here what I´ve done for other people with the same problem.

Notice I am using VS 2017:

-First of all, I deleted both ImiServicio.cs and miServicio.svc.cs

-Select current project/ add new element and then include a new WCF Service with AJAX enabled. You won´t need to create the interface this way.

-On new WCF, I added this code to the getSuma() method:

**[WebGet(ResponseFormat = WebMessageFormat.Xml)]**
    public int getSuma(int numero1, int numero2)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType =  "text/xml";
            return numero1 + numero2;
        }

The line "WebOperationContext..." in the body of the method seems to be not mandatory, but VS suggested to include it so I did.

-Now, we go to the jQuery code and we change these line:

url:"http://localhost:50664/miServicio.svc"

Notice I am not calling the method on the old code, so do this:

url:"http://localhost:50664/miServicio.svc/getSuma"

-Next, on success function, replace this:

alert("ok "+ response);

With this:

/*use the text() jQuery method to obtain the value returned by the method*/
alert("ok "+$(response).text());

IMPORTANT: I still don´t know how to enable CORS by code so I had to use a firefox extension to avoid this problem, for the moment. If you don´t enable, you will get error despite response is OK (status 200).

Upvotes: 1

Related Questions