Get JSON in WCF

atifrehmat
 
on Dec 14, 2015 02:24 AM
2704 Views

I have an interface which contains the following code:

 

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
string InsertRecord(string name, string age);
In my service class I have the following code:
public string InsertRecord(string name, string age)
{
	//Insert data to db and get rows affected as a result
            return result;
}

Here I was expecting the simple JSON string which contains either 0 or 1. But I get an object. And another thing is that when I type service URL in browser it says “Endpoint not found” and in WCF client it says “Service metadata may not be accessible”. But actually service is running and inserting the data into db. Here is my config file code:

<system.serviceModel>
    <services>
      <service name="NewArchitecture.Service.Service1"
                        behaviorConfiguration="serviceBehavior">
        <endpoint address=""
                              binding="webHttpBinding"
                              contract="NewArchitecture.Service.IService1"
                              behaviorConfiguration="RESTEndpointBehavior"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="RESTEndpointBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 14, 2015 05:36 AM
on Dec 14, 2015 05:40 AM

Hi atifrehmat,

I have created sample that full-fill your requirement.

Refer the below for more details.

Make AJAX JSON call to ASP.Net WCF Service using jQuery and Javascript

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //Search
        $("#search").live("click", function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Services/Service.svc/GetCustomers") %>',
                data: '{"prefix": "' + $("#prefix").val() + '"}',
                processData: false,
                dataType: "json",
                success: function (response) {
                    var customers = eval(response.d);
                    var html = "";
                    $.each(customers, function () {
                        html += "<span>Name: " + this.Name + " Id: " + this.Id + "</span><br />";
                    });
                    $("#results").html(html == "" ? "No results" : html);
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        });

        //Insert
        $("#save").live("click", function () {
            var name = $.trim($("[id*=txtName]").val());
            var country = $.trim($("[id*=txtCountry]").val());
            var Insert = {};
            Insert.name = name;
            Insert.country = country;
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Services/Service.svc/InsertRecord") %>',
                data: JSON.stringify(Insert), //'{"name": "' + name + '","country": "' + country + '"}',
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="text" id="prefix" />
    <input id="search" type="button" value="Search" />
    <div id="results">
    </div>
    <div>
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
            <tr>
                <td>
                    Country
                </td>
                <td>
                    <input type="text" id="txtCountry" />
                </td>
            </tr>
            <tr>
                <td>
                    <input id="save" type="button" value="Save" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Service.cs

public string GetCustomers(string prefix)
{
    List<object> customers = new List<object>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select Name, CustomerId from Customers where " +
            "Name like @prefix + '%'";
            cmd.Parameters.AddWithValue("@prefix", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new
                    {
                        Id = sdr["CustomerId"],
                        Name = sdr["Name"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(customers));
    }
}
public string InsertRecord(string name, string country)
{
    int result;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers (Name, Country) VALUES (@Name, @Country)"))
        {
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@Country", country);
            cmd.Connection = con;
            con.Open();
            result = cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return new JavaScriptSerializer().Serialize(result);
}

IService.cs

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
string GetCustomers(string prefix);

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
string InsertRecord(string name, string country);

Config file

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>