Como: Expor um feed como Atom e RSS
O Windows Communication Foundation (WCF) permite criar um serviço que expõe um feed de distribuição. Este tópico discute como criar um serviço de distribuição que expõe um feed de distribuição usando o Atom 1.0 e o RSS 2.0. Este serviço expõe um ponto de extremidade que pode retornar qualquer formato de distribuição. Para simplificar, o serviço usado neste exemplo é auto-hospedado. Em um ambiente de produção, um serviço desse tipo seria hospedado no IIS ou no WAS. Para obter mais informações sobre as diferentes opções de hospedagem do WCF, consulte Hospedagem.
Para criar um serviço de distribuição básico
Defina um contrato de serviço usando uma interface marcada com o WebGetAttribute atributo. Cada operação exposta como um feed de distribuição retorna um SyndicationFeedFormatter objeto. Observe os parâmetros para o WebGetAttributearquivo .
UriTemplate
especifica a URL usada para invocar essa operação de serviço. A cadeia de caracteres para este parâmetro contém literais e uma variável entre chaves ({format}). Esta variável corresponde ao parâmetro da operação deformat
serviço. Para obter mais informações, veja UriTemplate.BodyStyle
afeta a forma como as mensagens que esta operação de serviço envia e recebe são escritas. Bare especifica que os dados enviados de e para esta operação de serviço não são encapsulados por elementos XML definidos pela infraestrutura. Para obter mais informações, veja 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
Use o ServiceKnownTypeAttribute para especificar os tipos que são retornados pelas operações de serviço nesta interface.
Implementar o contrato de prestação de serviços.
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
Crie um SyndicationFeed objeto e adicione um autor, uma categoria e uma descrição.
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")
Crie vários SyndicationItem objetos.
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)
Adicione os SyndicationItem objetos ao 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
Use o parâmetro format para retornar o formato solicitado.
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
Para hospedar o serviço
Crie um WebServiceHost objeto. A WebServiceHost classe adiciona automaticamente um ponto de extremidade no endereço base do serviço, a menos que um seja especificado no código ou na configuração. Neste exemplo, nenhum ponto de extremidade é especificado para que o ponto de extremidade padrão seja exposto.
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)
Abra o host de serviço, carregue o feed do serviço, exiba o feed e aguarde que o usuário pressione 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()
Para chamar GetBlog com um HTTP GET
Abra um navegador, digite o seguinte URL e pressione Enter:
http://localhost:8000/BlogService/GetBlog
.A URL contém o endereço base do serviço (
http://localhost:8000/BlogService
), o endereço relativo do ponto de extremidade e a operação de serviço a ser chamada.
Para chamar GetBlog() a partir do código
Crie um XmlReader com o endereço base e o método que você está chamando.
XmlReader reader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom");
Dim atomReader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog?format=atom")
Chame o método estático Load(XmlReader) , passando o XmlReader que você acabou de criar.
SyndicationFeed feed = SyndicationFeed.Load(reader);
Dim feed As SyndicationFeed = SyndicationFeed.Load(atomReader)
Isso invoca a operação de serviço e preenche uma nova SyndicationFeed com o formatador retornado da operação de serviço.
Acesse o objeto 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
Exemplo
A seguir está a lista de código completo para este exemplo.
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();
}
}
}
}
Compilando o código
Ao compilar o código anterior, consulte System.ServiceModel.dll e System.ServiceModel.Web.dll.