Как предоставить доступ к каналу в форматах Atom и RSS

Windows Communication Foundation (WCF) позволяет создать службу, которая предоставляет веб-канал синдикации. В этом разделе рассматривается процесс создания службы синдикации, предоставляющей веб-канал синдикации с помощью Atom 1.0 и RSS 2.0. Эта служба предоставляет одну конечную точку, которая может вернуть любой формат синдикации. В целях упрощения в данном образце используется резидентная служба. В рабочей среде служба такого типа размещается в IIS или WAS. Дополнительные сведения о различных вариантах размещения WCF см. в разделе "Размещение".

Создание базовой службы синдикации

  1. Определите контракт службы с помощью интерфейса, отмеченного атрибутом WebGetAttribute. Каждая операция, предоставляемая как веб-канал синдикации, возвращает объект SyndicationFeedFormatter. Обратите внимание на параметры для WebGetAttribute. UriTemplate указывает URL-адрес, используемый для вызова этой операции службы. Строка для этого параметра содержит литералы и переменную в фигурных скобках ({format}). Эта переменная соответствует параметру format операции службы. Дополнительные сведения см. в разделе UriTemplate. BodyStyle влияет на способ записи сообщений, отправляемых и получаемых этой операцией службы. 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. Откройте узел службы, загрузите веб-канал из службы, отобразите веб-канал и дождитесь нажатия клавиши ВВОД пользователем.

    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()
    

Вызов GetBlog с помощью HTTP GET

  1. Откройте браузер, введите следующий URL-адрес и нажмите клавишу ВВОД: http://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.

См. также