2

I'm pretty knew to the world of C#, XAML, Visual Studio etc and i need abit of help to understand how i can create a simple WCF web application that emits JSON, i'd also like to know how to test the output of that application aswell.

I've been hunting around and followed a couple of different blogs but had no luck so far. I found another post on here about this, but again my attempts fail lol

I think i am now at the point where i have just confused myself totally by looking at too many different examples and need some help from this great site :)

I'll try and provide you with as much code as i have already and hopefully i've done somethignt hat can be rescued!!

Massive thanks in advance for your help!!

Person.cs

namespace TestService
{
[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public int Age { get; set; }

    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }
}

}

MyTestService.svc.cs

    namespace TestService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TestService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string GetResults()
        {
            List<Person> results = new List<Person>();
            results.Add(new Person("Peyton", "Manning", 35));
            results.Add(new Person("Drew", "Brees", 31));
            results.Add(new Person("Tony", "Romo", 29));

            // Serialize the results as JSON
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(results.GetType());
            MemoryStream memoryStream = new MemoryStream();
            serializer.WriteObject(memoryStream, results);

            // Return the results serialized as JSON
            string json = Encoding.Default.GetString(memoryStream.ToArray());
            return json;
        }
    }

MyTestService.svc

<%@ ServiceHost Language="C#"
Service="TestService.MyTestService"
Factory="System.ServiceModel.Activation.ServiceHostFactory" %>

web.config

    <configuration>
    <connectionStrings>
      <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;      

       AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
      </connectionStrings>

     <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>
Community
  • 1
  • 1
domsbrown
  • 75
  • 2
  • 10

1 Answers1

4

You will not need to serialize the object you wish to return, .NET will handle this all for your behind the scenes.

Modify the GetResults method like so:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<Person> GetResults()
{
    List<Person> results = new List<Person>();
    results.Add(new Person("Peyton", "Manning", 35));
    results.Add(new Person("Drew", "Brees", 31));
    results.Add(new Person("Tony", "Romo", 29));

    return results;
}

Hope this helps.

jdavies
  • 12,784
  • 3
  • 33
  • 33
  • really, so i can get rid of the follwing?? // Serialize the results as JSON DataContractJsonSerializer serializer = new DataContractJsonSerializer(results.GetType()); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, results); // Return the results serialized as JSON string json = Encoding.Default.GetString(memoryStream.ToArray()); return json; – domsbrown Oct 21 '11 at 12:37
  • I've made the amendments thanks alot for the advice. Do you know how i can test the output of this application? Sory if thats a daft question – domsbrown Oct 21 '11 at 12:38
  • If you just need to see it returning the JSON you can invoke it using your browser: `http://path/TestService.svc/GetResults` – jdavies Oct 21 '11 at 12:43
  • currently when i run my app i get this error Microsoft JScript runtime error: 'JSON' is undefined :oS – domsbrown Oct 21 '11 at 12:44
  • ah i think thats because i am running it from VS, i tried http://localhost/TestService.svc/GetResults but the page is just blank. thanks – domsbrown Oct 21 '11 at 12:49
  • nah even with http://localhost:52002/TestService.svc/GetResults i get the JSON undefined error mate – domsbrown Oct 21 '11 at 12:57
  • message after message lol right the error was due to some add on i had installed on IE8, this is now resolved but now the page doesn't load get Server Error in '/' Application. screen – domsbrown Oct 21 '11 at 13:05
  • sorry its - The type 'TestService.MyTestService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found. – domsbrown Oct 21 '11 at 13:28
  • Your configuration seems incorrect. Also your .svc file contains the following reference: `Service="TestService.MyTestService"`, however your service name is `TestService` – jdavies Oct 21 '11 at 13:38
  • hi, i've added teh web.config file (if thats what you were refering to?? I don't think i've changed the Service name myself :S – domsbrown Oct 21 '11 at 13:50
  • I believe the problem is in the MyTestService.svc file. Try changing `Service="TestService.MyTestService"` to `Service="TestService.TestService"`. – jdavies Oct 21 '11 at 13:59
  • ooo, something new lol You have created a service. To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax: – domsbrown Oct 21 '11 at 14:09