Share via


WCF Service to return JSON

Question

Monday, November 17, 2008 9:24 PM

Hell guys

I am trying to create a basic test example leanring how return JSON formatted data from a WCF call. Here is what I did after following articles I found here and other sites:

** CONTRACT:**

namespace WCFService
{
    [ServiceContract(Namespace = "http://localhost:8000/Samples",SessionMode=SessionMode.Allowed)]
    public interface ICustomer
    {
        [OperationContract]
        void SetCustomer(Customer c);
        [OperationContract]       
        Customer GetCustomer(int customerID);
    }
}

TEST IMPLEMENTATION

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    [AspNetCompatibilityRequirements
        (RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CustomerService : ICustomer
    {
        private Customer _customer;
        #region ICustomer Members
       
        public void SetCustomer(Customer c)
        {
            _customer = c;
        }
       
        public Customer GetCustomer(int customerID)
        {
            return _customer;
        }

        #endregion
    }

 

CONFIGURATION:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>     
      <service name="WCFService.CustomerService" behaviorConfiguration="behavior2">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9000/servicemodelsamples"/>
            <add baseAddress="http://localhost:55959/WebHost"/>
          </baseAddresses>
        </host>
        <endpoint binding="netTcpBinding" bindingConfiguration="PortSharingBinding"
                  contract="WCFService.ICustomer" address="">         
        </endpoint>
        <endpoint address="address1" contract="WCFService.ICustomer" binding="basicHttpBinding">         
        </endpoint>
        <endpoint address="" behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
                  name="testName" contract="WCFService.ICustomer">         
        </endpoint>
        <endpoint address="mex"
                  binding="mexTcpBinding"
                  contract="IMetadataExchange"/>
      </service>     
    </services>
    <bindings>
      <netTcpBinding>
        <binding name="PortSharingBinding" portSharingEnabled="false" listenBacklog="10" maxConnections="10" >
          <security mode="None"></security>
        </binding>
      </netTcpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="behavior2" >
          <serviceMetadata httpGetEnabled="true" httpGetUrl="metaData"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel> 
</configuration>

 

My Question is...

  1. will this suffice the WCF part?
  2. This is a stand alone project. I create a new VS 2008 web project to hit this service and get JSON string. How can I do that? If I add a web service reference, then I don't get the ".svc" file that many examples are teaching.

Please help.

All replies (11)

Monday, November 24, 2008 3:22 AM ✅Answered

Hi,

If you want to return a JSON string you can simply create a WCF project and try this:

 [DataContract]
    public class Customer
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Name { get; set; }
    }

    public class Service1 : IService1
    {
        public string GetData()
        {
            Customer c = new Customer() { ID = 1, Name = "Allen Chen" };
            string json;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customer));
                ser.WriteObject(ms, c);
                json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt16(ms.Length));
            }

            return json;
        }

     
    }

 [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData();

    }

 


Saturday, November 29, 2008 4:42 AM ✅Answered

 Allen,

This post of yours is what I was looking for:

http://msdn.microsoft.com/en-us/library/bb924552.aspx

 

Thanks..this worked.


Monday, November 24, 2008 12:04 PM

wow...very interesting. I was trying to write one generic method that setting the return type --> JSON or something else through app.config...I will try this and see how it works. Thanks.

Also can you please show me how I can consume this? To understand better, I am looking to consume this in two ways:

1> a .aspx page using ScriptManager

2> a .html page...using httprequest (assuming this application is a pure html pages only)

 Thanks in advance.


Monday, November 24, 2008 11:50 PM

 Hi,

1> a .aspx page using ScriptManager

To do this I suggest you return the object instead of string. If string is returned we need to use eval to create the JavaScirpt object. It's not as simple as returning object directly. Here's the code:

WCF:

IService1.cs:

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

namespace WcfService1
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract(Namespace = "WcfService1")]
    public interface IService1
    {
        [WebGet]
        [OperationContract]
        Customer GetData();

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
 
}
 

 Service1.svc.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Activation;

namespace WcfService1
{
    [DataContract]
    public class Customer
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Name { get; set; }
    }

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public Customer  GetData()
        {
            Customer c = new Customer() { ID = 1, Name = "Allen Chen" };
            return c;

        }

     
    }
}
 

config:

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="default"/>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService1.Service1"
         behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint address="" binding="webHttpBinding"
          bindingConfiguration="default"
          contract="WcfService1.IService1"
          behaviorConfiguration="webScriptEnablingBehavior"/>
      </service>
    </services>
   
       
    <behaviors>
      <endpointBehaviors>
        <behavior name="webScriptEnablingBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
         
         
        </behavior>
      </serviceBehaviors>
    </behaviors>
   
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    </system.serviceModel>

 

aspx:

  <asp:ScriptManager ID="ScriptManager1" runat="server" >
        <Services>
        <asp:ServiceReference Path="~/Service1.svc" /></Services>
        </asp:ScriptManager>
       
  <script type="text/javascript">
function onSuccess(result){

alert(result.Name);
}
 
    var obj=new WcfService1.IService1();
    var q=obj.GetData(onSuccess);
 
    </script>

 

2> a .html page...using httprequest (assuming this application is a pure html pages only)

As to above sample you can request following url:

http://localhost:31555/Service1.svc/GetData 

 

Please let me know if you have further questions. 


Tuesday, November 25, 2008 4:34 PM

 Thanks for the detailed response and yes I do have a couple of questions:

(i) When I add reference to my WCF service, I get a Reference.svcmap file (and not .svc file). What is the difference between the two and if I need the other one, how could I include? Right now I right click the solution, click on "add web service reference" and paste the url in my BASEADDRESS. This gets a reference.svcmap file in my solution.

(ii) looking at your example in javascript, when in debug mode if I get a WcfService1 is undefined. What would that mean?

 Thanks again for all the help.


Tuesday, November 25, 2008 4:43 PM

 Figured the address part and yes I was able to get to the method directly from browser by going to following:

http://localhost:55959/WebHost/address3/GetCustomer?customerID=aws

 I got the following JSON as a file saved to my hard drive.

{"d":{"__type":"Customer:#WCFService","Address":"asdnkjh","Age":21,"CustomerID":1,"Name":"customer123"}}

 

So I now need to know how to include this in my client app. I don't see the .svc file.

Please help!


Wednesday, November 26, 2008 2:17 PM

 If this helps, initially I did not create a WCF Web Service...but a regular project and started to include dlls as needed. That's why I did not have a .svc file to start with.

Any suggestions?


Wednesday, November 26, 2008 8:25 PM

Hi,

To create the WCF Service, right click your ASP.NET project icon in the solution explorer window, select Add->New Item and select the WCF Service template on the popup window, name it as "Service1.svc". Then click ok and paste the code into the relevant files as mentioned in my previous post .

 


Saturday, November 29, 2008 3:40 AM

 Allen,

Firstly, thanks for all the patience. I figured out why I was not seeing or able to add the .svc file..I was in a regular WCF project. As soon as I a WCF Web project, all was good. I got to that part where I am able to create and host the service. To add this to a client project here is what I do:

 - Create new asp.net web site.

- add reference to service created above: http://localhost:8343/WCFService1/Service.svc

- When I do that, I get  Service.discomap added to my client solution. Also within javascript when I create a new instance of my WcfService1.Customer (as shown in your example), I get a error. Would your example work if the WCF Service and client are in different projects (or solutions)? Also what am I doing wrong?

Thanks

D


Wednesday, July 29, 2009 1:57 AM

hello,

can't we do the same things without using JSON ?

As we dont require to parse text and all that.

so please tell me Why we need to use JSON in asp.net application.

what are other advance level usage of JSON ?

 

Thanks

Jony Shah


Wednesday, July 29, 2009 9:32 AM

Please just start a new thread. You misunderstood. This particular thread was specifically about JSON.