怎样创建启用Silverlight的WCF服务

This item was filled under [ 新闻News ]

 

 Silverlight能够消耗来自各种源码类型的数据,包括REST,API,ASMX服务,WCF服务和其他符合标准的服务。

美国1105集团供IT专家网专稿Silverlight能够消耗来自各种源码类型的数据,包括REST,API,ASMX服务,WCF服务和其他符合标准的服务。访问REST API中的数据对于想创建能够汇总和显示其他各类页面和服务中数据的混合应用程序的人来说总是充满吸引力的。

  然而,很多情况下,我们都想要对应用程序进行检索并以自己的数据显示应用程序。这种构想中所存在的不同选择包括ASMX服务,ADO.NET数据服务和WCF服务。让我们看看怎么用VS2008创建启用Silverlight的WCF服务。

  创建一个WCF服务

  WCF为客户绑定服务提供了若干不同的方法。你可以是用wsHttpBingding,netTcpBinding,basicHttpBinding和许多其他依照客户需求设计的应用程序。在Sliverlight2客户调用WCF服务的案例中,由于Silverlight2不支持使用WSSecurity标准来加密和解密SOAP信息的加密类,因此你需要使用basicHttpBinding。如果数据需要在客户端和服务器之间获得安全保障,可以使用SSL。虽然你可以创建一个WCF服务,然后手动改变服务配置文件的绑定。最简单的启动创建WCF服务的方法是使用VS2008的Add New Item对话中启用了Silverlight的WCF服务模板。通过使用这一模板,所有必须的配置选项都会自动创建以满足basicHttpBinding。图一展示了这一模板(一旦在VS中安装了Silverlight工具,就会看到启用WCF服务选项):

  怎样创建启用Silverlight的WCF服务

  在你创建新的Silverlight2项目或另一个Web对象的时候,系统会默认添加测试Web项目,你可以向测试Web项目中添加WCF服务。一旦完成添加,系统会对服务类做如下操作:

  

 

      [ServiceContract(Namespace = "")]  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  public class CustomerService

  {

  [OperationContract]

  public void DoWork()

  {

  // Add your operation implementation here

  return;

  }

  // Add more operations here and mark them with [OperationContract]

  }

 Silverlight2需要的basicHttpBinding会被自动添加到web.config,因此你不需要手动更改配置。(注意Silverlight3现在默认支持二进制信息编码因此性能更优良。)

  一旦WCF被添加到你的Web项目中,你就可以编写方法以便返回必需的对象,并能用WCF OperationContract属性对方法进行修饰。这一属性将这些方法标记为服务操作以便Silverlight客户能够使用这些方法。下面的代码是一个向返回Customer的对象添加名为GerCustomer服务操作的示例。虽然代码直接返回了Customer对象,但是你还是可以添加必要的代码以调用数据库和返回动态数据:

  

      [ServiceContract(Namespace = "http://www.TheWahlinGroup.com")]  [AspNetCompatibilityRequirements(RequirementsMode =

  AspNetCompatibilityRequirementsMode.Allowed)]

  public class CustomerService

  {

  [OperationContract]

  public Customer GetCustomer(int id)

  {

  return new Customer { FirstName = “John”, LastName = “Doe”, Zip = 85244 };

  }

  // Add more operations here and mark them with [OperationContract]

  }

  public class Customer

  {

  public string FirstName { get; set; }

  public string LastName { get; set; }

  public int Zip { get; set; }

  }

  显然,创建启用Silverlight的服务就像在VS 2008选择一个合适的模板一样简单。

喜欢这篇文章的人还喜欢。。。

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment

Anti-spam text: (Required) *
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text. Click to hear an audio file of the anti-spam word