共用方式為


作法:將摘要同時公開為 Atom 和 RSS

Windows Communication Foundation (WCF) 可讓您建立會公開新聞訂閱摘要的服務。 本主題討論如何同時使用 Atom 1.0 和 RSS 2.0,建立可公開新聞訂閱摘要的新聞訂閱服務。 此服務會公開可傳回任何一種新聞訂閱格式的端點。 為了簡要說明,此範例中使用的服務為自我裝載。 在實際執行環境中,此類型的服務會在 IIS 或 WAS 下裝載。 如需不同 WCF 裝載選項的詳細資訊,請參閱裝載

若要建立基本新聞訂閱服務

  1. 使用以 WebGetAttribute 屬性標記的介面來定義服務合約。 每個公開為新聞訂閱摘要的作業,都會傳回 SyndicationFeedFormatter 物件。 請注意 WebGetAttribute 的參數。 UriTemplate 會指定用來叫用此服務作業的 URL。 此參數字串使用大括號 ({format}) 來包含常值和變數。 此變數對應至服務作業的 format 參數。 如需詳細資訊,請參閱UriTemplateBodyStyle 會影響此服務作業所傳送與接收之訊息的寫入方式。 Bare 會指定傳送至此服務作業,以及來自此服務作業的資料都不得透過基礎結構定義的 XML 元素來包裝。 如需詳細資訊,請參閱WebMessageBodyStyle

    [ServiceContract]
    [ServiceKnownType(typeof(Atom10FeedFormatter))]
    [ServiceKnownType(typeof(Rss20FeedFormatter))]
    public interface IBlog
    {
        [OperationContract]
        [WebGet(UriTemplate = "GetBlog?format={format}")]
        SyndicationFeedFormatter GetBlog(string format);
    }
    
    <ServiceContract()> _
    <ServiceKnownType(GetType(Atom10FeedFormatter))> _
    <ServiceKnownType(GetType(Rss20FeedFormatter))> _
    Public Interface IBlog
        <OperationContract()> _
        <WebGet(UriTemplate:="GetBlog?format={format}")> _
        Function GetBlog(ByVal format As String) As SyndicationFeedFormatter
    End Interface
    

    注意

    請使用 ServiceKnownTypeAttribute 來指定此介面中由服務作業所傳回的型別。

  2. 實作服務合約。

    public class BlogService : IBlog
    {
        public SyndicationFeedFormatter GetBlog(string format)
        {
            SyndicationFeed feed = new SyndicationFeed("My Blog Feed", "This is a test feed", new Uri("http://SomeURI"));
            feed.Authors.Add(new SyndicationPerson("someone@microsoft.com"));
            feed.Categories.Add(new SyndicationCategory("How To Sample Code"));
            feed.Description = new TextSyndicationContent("This is a sample that demonstrates how to expose a feed through RSS and Atom with WCF");
            SyndicationItem item1 = new SyndicationItem(
                "Item One",
                "This is the content for item one",
                new Uri("http://localhost/Content/One"),
                "ItemOneID",
                DateTime.Now);
    
            SyndicationItem item2 = new SyndicationItem(
                "Item Two",
                "This is the content for item two",
                new Uri("http://localhost/Content/Two"),
                "ItemTwoID",
                DateTime.Now);
    
            SyndicationItem item3 = new SyndicationItem(
                "Item Three",
                "This is the content for item three",
                new Uri("http://localhost/Content/three"),
                "ItemThreeID",
                DateTime.Now);
            List<SyndicationItem> items = new List<SyndicationItem>();
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);
    
            feed.Items = items;
    
            if (format == "rss")
                return new Rss20FeedFormatter(feed);
            else if (format == "atom")
                return new Atom10FeedFormatter(feed);
            else return null;
        }
    }
    
    Public Class BlogService
        implements IBlog
    
        Public Function GetBlog(ByVal format As String) As SyndicationFeedFormatter Implements IBlog.GetBlog
            Dim feed As New SyndicationFeed("My Blog Feed", "This is a test feed", New Uri("http://SomeURI"))
            feed.Authors.Add(New SyndicationPerson("someone@microsoft.com"))
            feed.Categories.Add(New SyndicationCategory("How To Sample Code"))
            feed.Description = New TextSyndicationContent("This is a sample that demonstrates how to expose a feed through RSS and Atom with WCF")
            Dim item1 As New SyndicationItem( _
                "Item One", _
                "This is the content for item one", _
                New Uri("http://localhost/Content/One"), _
                "ItemOneID", _
                DateTime.Now)
    
            Dim item2 As New SyndicationItem( _
                "Item Two", _
                "This is the content for item two", _
                New Uri("http://localhost/Content/Two"), _
                "ItemTwoID", _
                DateTime.Now)
    
            Dim item3 As New SyndicationItem( _
                "Item Three", _
                "This is the content for item three", _
                New Uri("http://localhost/Content/three"), _
                "ItemThreeID", _
                DateTime.Now)
            Dim items As New List(Of SyndicationItem)()
            items.Add(item1)
            items.Add(item2)
            items.Add(item3)
    
            feed.Items = items
    
            If (format = "rss") Then
                Return New Rss20FeedFormatter(feed)
            Else
                Return New Atom10FeedFormatter(feed)
            End If
        End Function
    End Class
    
  3. 建立 SyndicationFeed 物件並新增作者、分類和描述。

    SyndicationFeed feed = new SyndicationFeed("My Blog Feed", "This is a test feed", new Uri("http://SomeURI"));
    feed.Authors.Add(new SyndicationPerson("someone@microsoft.com"));
    feed.Categories.Add(new SyndicationCategory("How To Sample Code"));
    feed.Description = new TextSyndicationContent("This is a sample that demonstrates how to expose a feed through RSS and Atom with WCF");
    
    Dim feed As New SyndicationFeed("My Blog Feed", "This is a test feed", New Uri("http://SomeURI"))
    feed.Authors.Add(New SyndicationPerson("someone@microsoft.com"))
    feed.Categories.Add(New SyndicationCategory("How To Sample Code"))
    feed.Description = New TextSyndicationContent("This is a sample that demonstrates how to expose a feed through RSS and Atom with WCF")
    
  4. 建立幾個 SyndicationItem 物件。

    SyndicationItem item1 = new SyndicationItem(
        "Item One",
        "This is the content for item one",
        new Uri("http://localhost/Content/One"),
        "ItemOneID",
        DateTime.Now);
    
    SyndicationItem item2 = new SyndicationItem(
        "Item Two",
        "This is the content for item two",
        new Uri("http://localhost/Content/Two"),
        "ItemTwoID",
        DateTime.Now);
    
    SyndicationItem item3 = new SyndicationItem(
        "Item Three",
        "This is the content for item three",
        new Uri("http://localhost/Content/three"),
        "ItemThreeID",
        DateTime.Now);
    
    Dim item1 As New SyndicationItem( _
        "Item One", _
        "This is the content for item one", _
        New Uri("http://localhost/Content/One"), _
        "ItemOneID", _
        DateTime.Now)
    
    Dim item2 As New SyndicationItem( _
        "Item Two", _
        "This is the content for item two", _
        New Uri("http://localhost/Content/Two"), _
        "ItemTwoID", _
        DateTime.Now)
    
    Dim item3 As New SyndicationItem( _
        "Item Three", _
        "This is the content for item three", _
        New Uri("http://localhost/Content/three"), _
        "ItemThreeID", _
        DateTime.Now)
    
  5. 新增 SyndicationItem 物件至摘要。

    List<SyndicationItem> items = new List<SyndicationItem>();
    items.Add(item1);
    items.Add(item2);
    items.Add(item3);
    
    feed.Items = items;
    
    Dim items As New List(Of SyndicationItem)()
    items.Add(item1)
    items.Add(item2)
    items.Add(item3)
    
    feed.Items = items
    
  6. 使用格式參數來傳回要求的格式。

    if (format == "rss")
        return new Rss20FeedFormatter(feed);
    else if (format == "atom")
        return new Atom10FeedFormatter(feed);
    else return null;
    
    If (format = "rss") Then
        Return New Rss20FeedFormatter(feed)
    Else
        Return New Atom10FeedFormatter(feed)
    End If
    

若要裝載服務

  1. 建立 WebServiceHost 物件。 除非在程式碼或組態中指定端點,否則 WebServiceHost 類別會在服務的基底位址上自動加入端點。 在這個範例中,沒有指定端點,因此會公開預設端點。

    Uri address = new Uri("http://localhost:8000/BlogService/");
    WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), address);
    
    Dim address As New Uri("http://localhost:8000/BlogService/")
    Dim svcHost As New WebServiceHost(GetType(BlogService), address)
    
  2. 開啟服務主機、從服務載入摘要、顯示摘要,並等候使用者按下 ENTER。

    svcHost.Open();
    Console.WriteLine("Service is running");
    
    Console.WriteLine("Loading feed in Atom 1.0 format.");
    XmlReader atomReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom");
    SyndicationFeed atomFeed = SyndicationFeed.Load(atomReader);
    Console.WriteLine(atomFeed.Title.Text);
    Console.WriteLine("Items:");
    foreach (SyndicationItem item in atomFeed.Items)
    {
        Console.WriteLine("Title: {0}", item.Title.Text);
        Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text);
    }
    
    Console.WriteLine("Loading feed in RSS 2.0 format.");
    XmlReader rssReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=rss");
    SyndicationFeed rssFeed = SyndicationFeed.Load(rssReader);
    Console.WriteLine(rssFeed.Title.Text);
    Console.WriteLine("Items:");
    foreach (SyndicationItem item in rssFeed.Items)
    {
        Console.WriteLine("Title: {0}", item.Title.Text);
        // Notice we are using item.Summary here instead of item.Content. This is because
        // of the differences between Atom 1.0 and RSS 2.0 specs.
        Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Summary).Text);
    }
    
    Console.WriteLine("Press <ENTER> to quit...");
    Console.ReadLine();
    svcHost.Close();
    
    svcHost.Open()
    Console.WriteLine("Service is running")
    
    Console.WriteLine("Loading feed in Atom 1.0 format.")
    Dim atomReader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom")
    Dim atomFeed As SyndicationFeed = SyndicationFeed.Load(atomReader)
    Console.WriteLine(atomFeed.Title.Text)
    Console.WriteLine("Items:")
    For Each item As SyndicationItem In atomFeed.Items
        Console.WriteLine("Title: {0}", item.Title.Text)
        Console.WriteLine("Content: {0}", CType(item.Content, TextSyndicationContent).Text)
    Next
    
    Console.WriteLine("Loading feed in RSS 2.0 format.")
    Dim rssReader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=rss")
    Dim rssFeed As SyndicationFeed = SyndicationFeed.Load(rssReader)
    Console.WriteLine(rssFeed.Title.Text)
    Console.WriteLine("Items:")
    For Each item As SyndicationItem In rssFeed.Items
        Console.WriteLine("Title: {0}", item.Title.Text)
        Console.WriteLine("Content: {0}", CType(item.Content, TextSyndicationContent).Text)
    Next
    
    
    Console.WriteLine("Press <ENTER> to quit...")
    Console.ReadLine()
    svcHost.Close()
    

若要使用 HTTP GET 呼叫 GetBlog

  1. 開啟瀏覽器,輸入下列 URL,然後按 Enterhttp://localhost:8000/BlogService/GetBlog

    URL 包含服務的基底位址 (http://localhost:8000/BlogService)、端點的相對位址,以及要呼叫的服務作業。

若要從程式碼呼叫 GetBlog()

  1. 使用基底位址與您要呼叫的方法建立 XmlReader

    XmlReader reader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom");
    
    Dim atomReader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom")
    
  2. 呼叫靜態 Load(XmlReader) 方法,傳入剛才建立的 XmlReader

    SyndicationFeed feed = SyndicationFeed.Load(reader);
    
    Dim feed As SyndicationFeed = SyndicationFeed.Load(atomReader)
    

    這會叫用服務作業,並在新的 SyndicationFeed 中填入服務作業所傳回的格式器。

  3. 存取摘要物件。

    Console.WriteLine(feed.Title.Text);
    Console.WriteLine("Items:");
    foreach (SyndicationItem item in feed.Items)
    {
        Console.WriteLine("Title: {0}", item.Title.Text);
        Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text);
    }
    
    Console.WriteLine(feed.Title.Text)
    Console.WriteLine("Items:")
    For Each item As SyndicationItem In feed.Items
        Console.WriteLine("Title: {0}", item.Title.Text)
        Console.WriteLine("Content: {0}", (CType(item.Content, TextSyndicationContent).Text))
    Next
    

範例

以下是這個範例的完整程式碼清單。

using System;
using System.Xml;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Syndication;
using System.ServiceModel.Web;
namespace Service
{
    [ServiceContract]
    [ServiceKnownType(typeof(Atom10FeedFormatter))]
    [ServiceKnownType(typeof(Rss20FeedFormatter))]
    public interface IBlog
    {
        [OperationContract]
        [WebGet(UriTemplate = "GetBlog?format={format}")]
        SyndicationFeedFormatter GetBlog(string format);
    }

    public class BlogService : IBlog
    {
        public SyndicationFeedFormatter GetBlog(string format)
        {
            SyndicationFeed feed = new SyndicationFeed("My Blog Feed", "This is a test feed", new Uri("http://SomeURI"));
            feed.Authors.Add(new SyndicationPerson("someone@microsoft.com"));
            feed.Categories.Add(new SyndicationCategory("How To Sample Code"));
            feed.Description = new TextSyndicationContent("This is a sample that demonstrates how to expose a feed through RSS and Atom with WCF");
            SyndicationItem item1 = new SyndicationItem(
                "Item One",
                "This is the content for item one",
                new Uri("http://localhost/Content/One"),
                "ItemOneID",
                DateTime.Now);

            SyndicationItem item2 = new SyndicationItem(
                "Item Two",
                "This is the content for item two",
                new Uri("http://localhost/Content/Two"),
                "ItemTwoID",
                DateTime.Now);

            SyndicationItem item3 = new SyndicationItem(
                "Item Three",
                "This is the content for item three",
                new Uri("http://localhost/Content/three"),
                "ItemThreeID",
                DateTime.Now);
            List<SyndicationItem> items = new List<SyndicationItem>();
            items.Add(item1);
            items.Add(item2);
            items.Add(item3);

            feed.Items = items;

            if (format == "rss")
                return new Rss20FeedFormatter(feed);
            else if (format == "atom")
                return new Atom10FeedFormatter(feed);
            else return null;
        }
    }

    public class Host
    {
        static void Main(string[] args)
        {
            Uri address = new Uri("http://localhost:8000/BlogService/");
            WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), address);
            try
            {
                svcHost.Open();
                Console.WriteLine("Service is running");

                Console.WriteLine("Loading feed in Atom 1.0 format.");
                XmlReader atomReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom");
                SyndicationFeed atomFeed = SyndicationFeed.Load(atomReader);
                Console.WriteLine(atomFeed.Title.Text);
                Console.WriteLine("Items:");
                foreach (SyndicationItem item in atomFeed.Items)
                {
                    Console.WriteLine("Title: {0}", item.Title.Text);
                    Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text);
                }

                Console.WriteLine("Loading feed in RSS 2.0 format.");
                XmlReader rssReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=rss");
                SyndicationFeed rssFeed = SyndicationFeed.Load(rssReader);
                Console.WriteLine(rssFeed.Title.Text);
                Console.WriteLine("Items:");
                foreach (SyndicationItem item in rssFeed.Items)
                {
                    Console.WriteLine("Title: {0}", item.Title.Text);
                    // Notice we are using item.Summary here instead of item.Content. This is because
                    // of the differences between Atom 1.0 and RSS 2.0 specs.
                    Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Summary).Text);
                }

                Console.WriteLine("Press <ENTER> to quit...");
                Console.ReadLine();
                svcHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                svcHost.Abort();
            }
        }
    }
}

編譯程式碼

在編譯先前的程式碼時,請參考 System.ServiceModel.dll 和 System.ServiceModel.Web.dll。

另請參閱