技术开发 频道

使用WCF和.NET 3.5 进行HTTP编程

  SyndicationItem 类型包含了超过 35 个成员。许多这些成员都是与设置或检索字段(如项目标识符、最后更新时间、发表日期、标题或实际内容)相关的属性。还有许多成员则是为了方便扩展 SyndicationItem 中存储的内容。对 RSS 和 ATOM 的扩展(Microsoft 简单列表扩展、Yahoo Media RSS、GeoRSS 等)有很多,SyndicationFeed 和 SyndicationItem 均可扩展为包含任何现有的 RSS 或 ATOM 扩展。

  源可以有许多项目,对于大型源来说,不能一次加载所有项目。SyndicationFeed 解决了这个情况,它将其 SyndicationItem 对象集公开为一个 IEnumerable<SyndicationItem>。这种实现使处理大量 SyndicationItem 对象更为方便,因为它充分利用了 .NET Framework 2.0 的迭代器功能。用 LINQ 也可以遍历一组 SyndicationItem 对象。这就大大减少了从源提取信息所需的代码量。
整合 API 定义了多个类型,它们可以将 SyndicationFeed 转换为 RSS 2.0 和 ATOM 1.0 格式。事实上,您可以构建 SyndicationFeed,用 SyndicationItem 对象填充它,然后将该源公开为 RSS 和 ATOM。图 5 演示了如何检索一个 ATOM 1.0 源、将其转换为 RSS 2.0,然后将新的 RSS 表示输出到控制台。

Figure 5 Transforming a Feed

// read an ATOM feed
Uri feedUri = new Uri("http://blogs.msdn.com/justinjsmith/atom.xml");
SyndicationFeed feed
= SyndicationFeed.Load(feedUri);

// transform it to RSS
Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed);
XmlWriter writer
= XmlWriter.Create(Console.Out, null);

// write it to the Console
formatter.WriteTo(writer);
writer.Flush();

  在 WCF 中将整合 API 与 HTTP 编程模型配合使用时,就可以公开来自自定义 URI 的源,并根据 URI 的构成返回 RSS 或者 ATOM。图 6 显示了如何在服务约定中定义一个操作,该操作将使用已收到的 HTTP GET 中的一个查询字符串参数来返回 RSS 或 ATOM 源。请注意操作约定中 SyndicationFeedFormatter<SyndicationFeed> 的使用。Rss20FeedFormatter 和 Atom10FeedFormatter 都派生于 SyndicationFeedFormatter<TSyndicationFeed>。

Figure 6 Exposing a Feed from a Customized URI

[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(
typeof(Rss20FeedFormatter))]
[ServiceContract]
interface IPictureService {
  [OperationContract]
  [WebGet(UriTemplate
="Pictures?format={format}")]
  SyndicationFeedFormatter
<SyndicationFeed> Feed(String format);
}

class PictureService : IPictureService {

  
public SyndicationFeedFormatter<SyndicationFeed> Feed(String format){
    
// create the syndication feed
    SyndicationFeed feed = new SyndicationFeed();

    
// add the items to the feed (omitted)

    
// check the argument & return the right format
    if(format.ToLower() == "rss"){
      
return new Rss20FeedFormatter(feed);
    }
    
return new Atom10FeedFormatter(feed);

  }

}

  总结

  总的来说,您已了解了 HTTP 传输的一些基础知识、它如何与 Web 原则相关联、如何使用 WCF 将这些原则结合到您的应用程序中,以及如何使用新的整合 API 来提供和使用 RSS 以及 ATOM 源。为了进一步演示这些新功能,您可以在一个名为 PictureServices 的示例应用程序(网址为 www.cloudsamples.net/pictureservices)中看到所有功能一起运行。您可以在线运行这个示例、浏览其源代码并下载整个示例。图 7 显示了运行中的 PictureServices。
Figure 7 The PictureServices Feed (单击该图像获得较大视图)
  简言之,PictureServices 可以从本地计算机或 Flickr 源检索图片。该应用程序使用一个简单的提供程序模型,目前有三个提供程序:Windows 桌面搜索、文件系统上的文件夹,以及 Flickr。一旦 PictureServices 从某个提供程序检索到文件,它便会整合这些图片,并且在本地提供它们。您可以在浏览器中单击一个源,然后检索各个图片。示例中还有许多内容,请尽情探索吧。有关本文所述技术的详细信息链接,请参阅“其他资源”侧栏。
0
相关文章