Stand-Alone 诊断数据流示例

DiagnosticsFeed 示例演示如何创建 RSS/Atom 源以联合 Windows Communication Foundation (WCF)。 它是一个基本的“Hello World”程序,它显示了对象模型的基础知识以及如何在 Windows Communication Foundation (WCF) 服务上设置它。

WCF 将联合供稿建模为返回特殊数据类型的服务操作。 SyndicationFeedFormatter SyndicationFeedFormatter 的实例可以将 feed 序列化为 RSS 2.0 和 Atom 1.0 格式。 下面的示例代码显示了使用的协定。

[ServiceContract(Namespace = "")]
    interface IDiagnosticsService
    {
        [OperationContract]
        //The [WebGet] attribute controls how WCF dispatches
        //HTTP requests to service operations based on a URI suffix
        //(the part of the request URI after the endpoint address)
        //using the HTTP GET method. The UriTemplate specifies a relative
        //path of 'feed', and specifies that the format is
        //supplied using a query string.
        [WebGet(UriTemplate="feed?format={format}")]
        [ServiceKnownType(typeof(Atom10FeedFormatter))]
        [ServiceKnownType(typeof(Rss20FeedFormatter))]
        SyndicationFeedFormatter GetProcesses(string format);
    }

GetProcesses操作使用WebGetAttribute属性进行了标注,使你能够控制 WCF 如何调度 HTTP GET 请求到服务操作,并指定发送的消息格式。

如同任何 WCF 服务一样,联合源可以自承载于任何托管应用程序中。 联合服务需要特定的绑定(the WebHttpBinding)和特定的终结点行为(the WebHttpBehavior)才能正常运行。 新 WebServiceHost 类提供了一个方便的 API,用于创建此类终结点,而无需特定配置。

WebServiceHost host = new WebServiceHost(typeof(ProcessService), new Uri("http://localhost:8000/diagnostics"));

            //The WebServiceHost will automatically provide a default endpoint at the base address
            //using the proper binding (the WebHttpBinding) and endpoint behavior (the WebHttpBehavior)

或者,可以从 IIS 托管的 .svc 文件中使用 WebServiceHostFactory 提供等效功能(本示例代码中未演示此技术)。

<% @ServiceHost Language="C#|VB" Debug="true" Service="ProcessService" %>

由于此服务使用标准 HTTP GET 接收请求,因此可以使用任何 RSS 或 ATOM 感知客户端访问服务。 例如,您可以在支持 RSS 的浏览器中通过导航到 http://localhost:8000/diagnostics/feed/?format=atomhttp://localhost:8000/diagnostics/feed/?format=rss 来查看此服务的输出。

还可以使用 WCF 联合对象模型如何映射到 Atom 和 RSS 来读取联合数据,并使用命令性代码对其进行处理。

XmlReader reader = XmlReader.Create( "http://localhost:8000/diagnostics/feed/?format=rss",
    new XmlReaderSettings()
    {
        //MaxCharactersInDocument can be used to control the maximum amount of data
        //read from the reader and helps prevent OutOfMemoryException
        MaxCharactersInDocument = 1024 * 64
    } );

SyndicationFeed feed = SyndicationFeed.Load(reader);

foreach (SyndicationItem i in feed.Items)
{
    XmlSyndicationContent content = i.Content as XmlSyndicationContent;
    ProcessData pd = content.ReadContent<ProcessData>();

    Console.WriteLine(i.Title.Text);
    Console.WriteLine(pd.ToString());
}

设置、生成和运行示例

  1. 确保计算机上具有 HTTP 和 HTTPS 的正确地址注册权限,如 Windows Communication Foundation 示例One-Time 安装过程中的设置说明中所述。

  2. 生成解决方案。

  3. 运行控制台应用程序。

  4. 在控制台应用程序运行时,使用支持 RSS 的浏览器导航到 http://localhost:8000/diagnostics/feed/?format=atomhttp://localhost:8000/diagnostics/feed/?format=rss

另请参阅