什么是制作Silverlight和Regular .NET REST客户端最便携的方法

dam*_*boy 5 .net rest wcf silverlight-2.0 .net-3.5

我试图让服务器应用程序使用WCF公开一些状态信息.特别是我在使用RESTful"API"的WCF服务之后.当我从一个Silverlight应用程序/页面中使用REST api时,我正在尝试使用另一种类型的客户端...

到目前为止,我已经成功定义了一个状态界面:

public static class StatusUriTemplates
{
  public const string Status = "/current-status";
  public const string StatusJson = "/current-status/json";
  public const string StatusXml = "/current-status/xml";
}
[ServiceContract]
public interface IStatusService
{
  [OperationContract]
  [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = StatusUriTemplates.StatusJson)]
  StatusResultSet GetProgressAsJson();

  [OperationContract]
  [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = StatusUriTemplates.StatusXml)]
  StatusResultSet GetProgressAsXml();

  [OperationContract]
  [WebGet(UriTemplate = StatusUriTemplates.Status)]
  StatusResultSet GetProgress();
}
Run Code Online (Sandbox Code Playgroud)

在服务器中实现它:

  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  public class ServerStatusService : IStatusService
  {
    public StatusResultSet GetProgressAsJson()
    { return GetProgress(); }

    public StatusResultSet GetProgressAsXml()
    { return GetProgress(); }

    public StatusResultSet GetProgress()
    {
       return StatusResultSet.Empty;
    }
  }
Run Code Online (Sandbox Code Playgroud)

在运行时从我的代码中公开它:

  var service = new ServerStatusService();
  var binding = new WebHttpBinding();
  var behavior = new WebHttpBehavior();

  var host = new WebServiceHost(service, new Uri("http://localhost:8000/server"));
  host.AddServiceEndpoint(typeof(IStatusService), binding, "status");
  host.Open();
Run Code Online (Sandbox Code Playgroud)

我甚至成功地使用.NET控制台/ winfoems/WPF应用程序中的服务使用了以下内容:

  var cf = new WebChannelFactory<IStatusService>(new Uri("http://localhost:8000/server/status"));
  var ss = cf.CreateChannel();
  Console.WriteLine(ss.GetProgress().TimeStamp);
Run Code Online (Sandbox Code Playgroud)

我正在打的"墙"是SliverLight没有WebChannelFactory.

期.

这意味着当涉及到silverlight代码时,我的选择是:

  • 使用WebClient编写丑陋的代码,这意味着每当我对API进行更改时,我将不得不更新两组代码
  • 将SOAP/WS用于WebService并继续从Visual Studio更新服务引用

有没有办法在SilverLight中使用WebChannelFactory保持"干净"的实现?也许SilverLight的公共域/开源WebChannelFactory?

任何有关这方面的帮助将不胜感激!

Rob*_*Rob 1

我几乎不想建议它,但您对重新实现 WebChannelFactory<T> 类感到满意吗?

粗略地浏览一下 Silverlight API,您似乎不会从 Microsoft 获得太多开箱即用的帮助。您需要为其重新实现一个通道类和一个工厂。

也许创建通道并将自己与特定于平台的代码隔离的另一种方法是创建它的自定义实现?具体来说,我的意思是,您创建另一个工厂类,该工厂类要么在 WebChannelFactory 可用时调用它,要么为您进行设置。

抱歉我没有更深入的建议。:)