Creación de una fuente básica de Atom
Windows Communication Foundation (WCF) le permite crear un servicio que exponga una fuente de distribución. En este tema se discute cómo crear un servicio de distribución que exponga una fuente de distribución Atom.
Creación de un servicio de distribución básico
Defina un contrato de servicios utilizando una interfaz marcada con el atributo WebGetAttribute. Cada operación que se expone como una fuente de distribución debería devolver un objeto Atom10FeedFormatter.
[ServiceContract] public interface IBlog { [OperationContract] [WebGet] Atom10FeedFormatter GetBlog(); }
Nota: Todas las operaciones de servicio que apliquen el WebGetAttribute se asignan a solicitudes HTTP GET. Para asignar su operación a un método HTTP diferente, utilice en su lugar WebInvokeAttribute. Para obtener más información, vea Cómo: Crear un servicio básico web HTTP de WCF. Implemente el contrato de servicios.
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 illistrates how to expose a feed using ATOM with WCF"); SyndicationItem item1 = new SyndicationItem( "Item One", "This is the content for item one", new Uri("https://localhost/Content/One"), "ItemOneID", DateTime.Now); SyndicationItem item2 = new SyndicationItem( "Item Two", "This is the content for item two", new Uri("https://localhost/Content/Two"), "ItemTwoID", DateTime.Now); SyndicationItem item3 = new SyndicationItem( "Item Three", "This is the content for item three", new Uri("https://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); } }
Cree un objeto SyndicationFeed y agregue un autor, categoría y descripción.
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 illistrates how to expose a feed using ATOM with WCF");
Cree varios objetos SyndicationItem.
SyndicationItem item1 = new SyndicationItem( "Item One", "This is the content for item one", new Uri("https://localhost/Content/One"), "ItemOneID", DateTime.Now); SyndicationItem item2 = new SyndicationItem( "Item Two", "This is the content for item two", new Uri("https://localhost/Content/Two"), "ItemTwoID", DateTime.Now); SyndicationItem item3 = new SyndicationItem( "Item Three", "This is the content for item three", new Uri("https://localhost/Content/three"), "ItemThreeID", DateTime.Now);
Agregue los objetos SyndicationItem a la fuente.
List<SyndicationItem> items = new List<SyndicationItem>(); items.Add(item1); items.Add(item2); items.Add(item3); feed.Items = items;
Devuelva la fuente.
return new Atom10FeedFormatter(feed);
Para hospedar el servicio.
Cree un objeto WebServiceHost.
Uri baseAddress = new Uri("https://localhost:8000/BlogService/"); WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), baseAddress);
Abra el host del servicio, cargue la fuente desde el servicio, muestre la fuente y espere a que el usuario presione Entrar.
svcHost.Open(); Console.WriteLine("Service is running"); XmlReader reader = XmlReader.Create("https://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();
Realización de llamadas a GetBlog() mediante HTTP GET
Abra Internet Explorer, escriba la siguiente URL y presione Entrar: https://localhost:8000/BlogService/GetBlog
La URL contiene la dirección base del servicio (https://localhost:8000/BlogService), la dirección relativa del extremo y la operación del servicio que se va a llamar.
Llamar a GetBlog() mediante código
Cree un XmlReader con la dirección base y el método al que está llamando.
XmlReader reader = XmlReader.Create("https://localhost:8000/BlogService/GetBlog");
Llame al método estático Load, pasando el XmlReader que acaba de crear.
SyndicationFeed feed = SyndicationFeed.Load(reader);
Esto invoca la operación de servicio y rellena una nueva SyndicationFeed con el formateador devuelto desde la operación del servicio.
Obtenga acceso al objeto de fuente.
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); }
Ejemplo
A continuación, se muestra una lista de código completa en este ejemplo.
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 illistrates how to expose a feed using ATOM with WCF");
SyndicationItem item1 = new SyndicationItem(
"Item One",
"This is the content for item one",
new Uri("https://localhost/Content/One"),
"ItemOneID",
DateTime.Now);
SyndicationItem item2 = new SyndicationItem(
"Item Two",
"This is the content for item two",
new Uri("https://localhost/Content/Two"),
"ItemTwoID",
DateTime.Now);
SyndicationItem item3 = new SyndicationItem(
"Item Three",
"This is the content for item three",
new Uri("https://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("https://localhost:8000/BlogService/");
WebServiceHost svcHost = new WebServiceHost(typeof(BlogService), baseAddress);
try
{
svcHost.Open();
Console.WriteLine("Service is running");
XmlReader reader = XmlReader.Create("https://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();
}
}
}
}
Compilar el código
Al compilar el código anterior, haga referencia a System.ServiceModel.dll y System.ServiceModel.Web.dll.