Condividi tramite


Procedura: esporre un feed come Atom e RSS

Windows Communication Foundation (WCF) consente di creare un servizio che espone un feed di diffusione. In questo argomento viene illustrato come creare un servizio di diffusione che espone un feed di diffusione usando sia Atom 1.0 sia RSS 2.0. Questo servizio espone un endpoint che può restituire uno dei due formati di diffusione. Per motivi di semplicità, il servizio usato in questo esempio è indipendente. In un ambiente di produzione un servizio di questo tipo verrebbe ospitato da IIS o WAS. Per maggiori informazioni sulle diverse opzioni di hosting WCF, vedere Hosting.

Per creare un servizio di diffusione di base

  1. Definire un contratto di servizio usando un'interfaccia contrassegnata con l'attributo WebGetAttribute. Ogni operazione esposta come feed di diffusione restituisce un oggetto SyndicationFeedFormatter. Si notino i parametri per WebGetAttribute. UriTemplate specifica l'URL usato per richiamare questa operazione del servizio. La stringa di questo parametro contiene valori letterali e una variabile in parentesi graffe ({format}). Questa variabile corrisponde al parametro format dell'operazione del servizio. Per ulteriori informazioni, vedere UriTemplate. BodyStyle incide sul modo in cui vengono scritti i messaggi inviati e ricevuti da e verso questa operazione del servizio. Bare specifica che i dati inviati da e verso questa operazione del servizio non vengono incapsulati in elementi XML definiti dall'infrastruttura. Per ulteriori informazioni, vedere 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
    

    Nota

    Usare ServiceKnownTypeAttribute per specificare i tipi restituiti dalle operazioni del servizio in questa interfaccia.

  2. Implementare il contratto di servizio

    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. Creare un oggetto SyndicationFeed e aggiungere un autore, una categoria e una descrizione.

    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. Creare diversi oggetti 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. Aggiungere gli oggetti SyndicationItem al feed.

    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. Usare il parametro di formato per restituire il formato richiesto.

    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
    

Per ospitare il servizio

  1. Creare un oggetto WebServiceHost. La classe WebServiceHost aggiunge automaticamente un endpoint nell'indirizzo di base del servizio, a meno che non ne sia specificato uno nel codice o nella configurazione. Poiché in questo esempio non è specificato alcun endpoint, viene esposto l'endpoint predefinito.

    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. Aprire l'host del servizio, caricare il feed dal servizio, visualizzare il feed e aspettare che l'utente prema INVIO.

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

Per chiamare GetBlog con HTTP GET

  1. Aprire un browser, immettere l'URL seguente e premere Invio: http://localhost:8000/BlogService/GetBlog.

    L'URL contiene l'indirizzo di base del servizio (http://localhost:8000/BlogService), l'indirizzo relativo dell'endpoint e l'operazione del servizio da chiamare.

Per chiamare GetBlog() dal codice

  1. Creare un XmlReader con l'indirizzo di base e il metodo che si sta chiamando.

    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. Chiamare il metodo statico Load(XmlReader) passando l'oggetto XmlReader appena creato.

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

    Verrà in tal modo richiamata l'operazione del servizio e verrà popolato un nuovo SyndicationFeed con il formattatore restituito dall'operazione del servizio.

  3. Accedere all'oggetto feed.

    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
    

Esempio

Di seguito è riportato il codice completo per questo esempio.

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

Compilazione del codice

Durante la compilazione del codice precedente, fare riferimento a System.ServiceModel.dll e a System.ServiceModel.Web.dll.

Vedi anche