Como: Criar um feed de átomos básico
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 Atom.
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 deve retornar um Atom10FeedFormatter objeto.
[ServiceContract] public interface IBlog { [OperationContract] [WebGet] Atom10FeedFormatter GetBlog(); }
<ServiceContract()> _ Public Interface IBlog <OperationContract()> _ <WebGet> _ Function GetBlog() As Atom10FeedFormatter End Interface
Nota
Todas as operações de serviço que aplicam o WebGetAttribute são mapeadas para solicitações HTTP GET. Para mapear sua operação para um método HTTP diferente, use o em vez disso WebInvokeAttribute . Para obter mais informações, consulte Como criar um serviço básico WCF Web HTTP.
Implementar o contrato de prestação de serviços.
public class BlogService : IBlog { public Atom10FeedFormatter GetBlog() { SyndicationFeed feed = new SyndicationFeed("My Blog Feed", "This is a test feed", new Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now)); 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 illustrates how to expose a feed using 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; return new Atom10FeedFormatter(feed); } }
Public Class BlogService Implements IBlog Public Function GetBlog() As Atom10FeedFormatter Implements IBlog.GetBlog Dim feed As New SyndicationFeed("My Blog Feed", "This is a test feed", New Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now)) 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 illustrates how to expose a feed imports 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 Return New Atom10FeedFormatter(feed) 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"), "FeedOneID", new DateTimeOffset(DateTime.Now)); 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 illustrates how to expose a feed using ATOM with WCF");
Dim feed As New SyndicationFeed("My Blog Feed", "This is a test feed", New Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now)) 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 illustrates how to expose a feed imports 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
Devolva o feed.
return new Atom10FeedFormatter(feed);
Return New Atom10FeedFormatter(feed)
Para hospedar o serviço
Crie um WebServiceHost objeto.
Uri baseAddress = new Uri("http://localhost:8000/BlogService/"); WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), baseAddress);
Dim baseAddress As New Uri("http://localhost:8000/BlogService/") Dim svcHost As New WebServiceHost(GetType(BlogService), baseAddress)
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"); XmlReader reader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog"); SyndicationFeed feed = SyndicationFeed.Load(reader); 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("Press <ENTER> to quit..."); Console.ReadLine(); svcHost.Close();
svcHost.Open() Console.WriteLine("Service is running") Dim reader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog") Dim feed As SyndicationFeed = SyndicationFeed.Load(reader) 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}", item.Title.Text) Next Console.WriteLine("Press <ENTER> to quit...") Console.ReadLine() svcHost.Close()
Para chamar GetBlog() com um HTTP GET
Em um navegador da Web, navegue até o seguinte URL:
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");
Dim serviceAddress As New Uri("http://localhost:8000/BlogService/GetBlog")
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(serviceAddress)
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("Summary: {0}", ((TextSyndicationContent)item.Summary).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("Summary: {0}", item.Summary.Text) Next
Exemplo
A seguir está a lista de código completo para este exemplo.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.Xml;
using System.ServiceModel.Description;
using System.ServiceModel.Syndication;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
namespace Service
{
[ServiceContract]
public interface IBlog
{
[OperationContract]
[WebGet]
Atom10FeedFormatter GetBlog();
}
public class BlogService : IBlog
{
public Atom10FeedFormatter GetBlog()
{
SyndicationFeed feed = new SyndicationFeed("My Blog Feed", "This is a test feed", new Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now));
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 illustrates how to expose a feed using 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;
return new Atom10FeedFormatter(feed);
}
}
public class Host
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/BlogService/");
WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), baseAddress);
try
{
svcHost.Open();
Console.WriteLine("Service is running");
XmlReader reader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog");
SyndicationFeed feed = SyndicationFeed.Load(reader);
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("Press <ENTER> to quit...");
Console.ReadLine();
svcHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
svcHost.Abort();
}
}
}
}
Imports System.Xml
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Syndication
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Web
<ServiceContract()> _
Public Interface IBlog
<OperationContract()> _
<WebGet> _
Function GetBlog() As Atom10FeedFormatter
End Interface
Public Class BlogService
Implements IBlog
Public Function GetBlog() As Atom10FeedFormatter Implements IBlog.GetBlog
Dim feed As New SyndicationFeed("My Blog Feed", "This is a test feed", New Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now))
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 illustrates how to expose a feed imports 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
Return New Atom10FeedFormatter(feed)
End Function
End Class
Module Program
Sub Main()
Dim baseAddress As New Uri("http://localhost:8000/BlogService/")
Dim svcHost As New WebServiceHost(GetType(BlogService), baseAddress)
Try
svcHost.AddServiceEndpoint(GetType(IBlog), New WebHttpBinding(), "")
svcHost.Open()
Console.WriteLine("Service is running")
Dim reader As XmlReader = XmlReader.Create("http://localhost:8000/BlogService/GetBlog")
Dim feed As SyndicationFeed = SyndicationFeed.Load(reader)
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}", item.Title.Text)
Next
Console.WriteLine("Press <ENTER> to quit...")
Console.ReadLine()
svcHost.Close()
Catch ce As CommunicationException
Console.WriteLine("An exception occurred: {0}", ce.Message)
svcHost.Abort()
End Try
End Sub
End Module
Compilando o código
Ao compilar o código anterior, consulte System.ServiceModel.dll e System.ServiceModel.Web.dll.