发出JSON的WCF Web服务(Noob建议)

时间:2011-10-21 11:57:29

标签: c# wcf json visual-studio-2010

我非常了解C#,XAML,Visual Studio等世界,我需要帮助了解如何创建一个发出JSON的简单WCF Web应用程序,我也想知道如何测试该应用程序的输出也是如此。

我一直在四处寻找并跟踪了几个不同的blogs但到目前为止没有运气。我在这里发现了另一个post,但我的尝试再次失败大声笑

我认为我现在处于这样的地步,我只是通过查看太多不同的例子并需要这个伟大网站的帮助来完全迷惑自己:)

我会尝试为你提供尽可能多的代码,希望我已经完成了一些可以获救的帽子!

非常感谢您的帮助!!

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>

1 个答案:

答案 0 :(得分:4)

您不需要序列化您想要返回的对象,.NET将为您在幕后处理这一切。

修改GetResults方法,如下所示:

[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;
}

希望这有帮助。