1
votes

I am using asp.net. I have created an WCF service in C# and hosted on IIS server. I am calling this service using JQuery in my asp.net web application. When I called the service using JQuery, it is going to error function and in alert there is empty message.

Calling service form .aspx page.

<script src="Script/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">
function callService()
{
    var value = 10;
    $.ajax({
        type: "POST",
        url: "http://localhost/IISWCF/Service1.svc/getdata",
        contentType: "application/json; charset=utf-8",
        data: '{"value": "' + value + '"}',
        dataType: "json",
        processdata: true, //True or False
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error: " + errorThrown);
        },
        success: function(msg) {
            alert(msg.d);
        }
    });
}
</script>

<script type="text/javascript" language="javascript">
$(document).ready(function(){
    callService();
})
</script>

Service1.svc file

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

IService1.cs file

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);
    }
}

WCF Web.config file

    <system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfService1.Service1Behavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="EndpBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
      <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
        <identity>
          <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"   />
</system.serviceModel>

Please help me to resolved this issue.

1
Try to use the directions mentioned in this article, as it seems you might be requiring JSON as response. WebGet and WebInvoke seems to be missing. codeproject.com/Articles/132809/…Ashish Jain
I have followed the steps mentioned in the link and issue is not resolved. I have edited my question with new one. Can you help me.user2322512
Change endpoint binding to webHttpBindingErwin
I have change endpoint binding to webHttpBinding and still issue is not resolved. Any help.user2322512
When I was adding integer as param in DoubleUp it asked me to convert to string. So try executing the service methods by directly hitting the URL and then go for Ajax testing. If its working directly then there is some issue with Ajax Call.Ashish Jain

1 Answers

0
votes

I have added some dummy code, probably few methods are not used also. But you can test your code with the dummy DoubleUp method. Also, you have defined endpointbehavior, but is it used, it should be applied to endpoint and its important. Ref my example below.

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the     interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ICalculatorService
{

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DoubleUp/{val}")]
    int DoubleUp(string val);

    [OperationContract]
    [WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate="/{value}/{value1}")]
    int AddValues(string value, string value1);

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string ConcatenateString(string stringArray);
}  


public class CalculationService : ICalculatorService
{

    public int DoubleUp(string val)
    {
        return 2 * Convert.ToInt32(val);
    }

    public int AddValues(string value, string value1)
    {
        return Convert.ToInt32(value) + Convert.ToInt32(value1);
    }

    public string ConcatenateString(string stringArray)
    {
        string returnString = string.Empty;
        returnString += stringArray;           

        return returnString;
    }
}

<system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="JSONBinding"></binding>
  </webHttpBinding>
  <basicHttpBinding>
    <binding name="basicHTTP">
      <security mode="None">

      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="basicBehavior">
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="JSON">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
<service name="RestWCFService.CalculationService" behaviorConfiguration="basicBehavior">
    <endpoint address="basic" binding="basicHttpBinding" contract="RestWCFService.ICalculatorService" bindingName ="basicHTTP"></endpoint>
    <endpoint behaviorConfiguration="JSON" binding="webHttpBinding" bindingConfiguration="JSONBinding" contract="RestWCFService.ICalculatorService" name="JSONService"></endpoint>
  </service>      
</services>

<protocolMapping>
    <add binding="basicHttpBinding" scheme="http"/>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>



 /* This is the code for accessing the service via REST call
        WebClient client = new WebClient();
        string s = client.DownloadString("http://localhost/RestWCFService/CalculationService.svc/DoubleUp/3");
        Console.WriteLine("Response returned is:" + s);
        */

        /*This is the section to access service via Proxy */

        ChannelFactory<RestWCFService.ICalculatorService> client = new ChannelFactory<RestWCFService.ICalculatorService>();

        client.Endpoint.Address = new EndpointAddress("http://localhost/RestWCFService/CalculationService.svc/basic");
        client.Endpoint.Binding = new BasicHttpBinding();
        RestWCFService.ICalculatorService service = client.CreateChannel();

        int val = service.DoubleUp("2");
        ((IClientChannel)service).Close();
        client.Close();

        Console.WriteLine("Values returned is:" + val.ToString());

        /*Programmatic access ends here */

        Console.ReadLine();

Your service is working fine. Made some changes.

[ServiceContract]
public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate="/GetData?value={value}")]
    string GetData(int value);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

 <system.serviceModel>    
  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfService1.Service1Behavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="EndpBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
      <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
        <identity>
          <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"   />
</system.serviceModel>

Access the service on browser and you get the result.

http://localhost/IISWCF/Service1.svc/GetData?value=1

If your service is working fine, then try this JS as your JS is incorrect for this service request.

<script type="text/javascript" language="javascript">
function callService() {
    var value = 10;
    $.ajax({
        type: "GET",
        url: "http://localhost/IISWCF/Service1.svc/GetData?value=1",
        contentType: "application/json; charset=utf-8",
        data: '{"value": "' + value + '"}',
        dataType: "text",
        processdata: false, //True or False
        statusCode: {
            404: function () {
                alert("page not found");
            },
            200: function () {
                alert('HTTP HIT WAS Good.');
            },
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("error: " + errorThrown);
        },
        success: function (msg) {
            alert(msg);
        }
    });
}