獨立診斷摘要範例
DiagnosticsFeed 範例示範如何透過 Windows Communication Foundation (WCF) 來建立一個用於新聞訂閱的 RSS/Atom 摘要。 它是一個基本的 "Hello World" 程式,顯示了物件模型的基礎以及如何在 Windows Communication Foundation (WCF) 服務上設定它。
WCF 會將新聞訂閱摘要建模為傳回一個特殊資料類型 (SyndicationFeedFormatter) 的服務作業。 SyndicationFeedFormatter 的執行個體可將摘要序列化至 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 服務一樣,新聞訂閱摘要可以在任何受控應用程式中自行受託管。 新聞訂閱服務需要指定的繫結 (WebHttpBinding) 和指定的端點行為 (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=atom
或 http://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());
}
設定、建置及執行範例
確定您在電腦上擁有正確的 HTTP 和 HTTPS 位址註冊權限,如 [Windows Communication Foundation 範例的單次安裝程序] 中的安裝指示所述。
建置方案。
執行主控台應用程式 (Console Application)。
當主控台應用程式執行時,請使用 RSS 感知瀏覽器來瀏覽到
http://localhost:8000/diagnostics/feed/?format=atom
或http://localhost:8000/diagnostics/feed/?format=rss
。