You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ServiceModel.Syndication;
  4. using System.Web;
  5. using System.Xml;
  6. public class FeedHandler : IHttpHandler
  7. {
  8. public void ProcessRequest(HttpContext context)
  9. {
  10. SyndicationFeed feed = new SyndicationFeed()
  11. {
  12. Title = new TextSyndicationContent(Blog.Title),
  13. Description = new TextSyndicationContent("Latest blog posts"),
  14. BaseUri = new Uri(context.Request.Url.Scheme + "://" + context.Request.Url.Authority),
  15. Items = GetItems(),
  16. };
  17. feed.Links.Add(new SyndicationLink(feed.BaseUri));
  18. using (var writer = new XmlTextWriter(context.Response.Output))
  19. {
  20. var formatter = GetFormatter(context, feed);
  21. formatter.WriteTo(writer);
  22. }
  23. context.Response.ContentType = "text/xml";
  24. }
  25. private IEnumerable<SyndicationItem> GetItems()
  26. {
  27. foreach (Post p in Blog.GetPosts(10))
  28. {
  29. var item = new SyndicationItem(p.Title, p.Content, p.AbsoluteUrl, p.AbsoluteUrl.ToString(), p.LastModified);
  30. item.Authors.Add(new SyndicationPerson("", p.Author, ""));
  31. yield return item;
  32. }
  33. }
  34. private SyndicationFeedFormatter GetFormatter(HttpContext context, SyndicationFeed feed)
  35. {
  36. string path = context.Request.Path.Trim('/');
  37. int index = path.LastIndexOf('/');
  38. if (index > -1 && path.Substring(index + 1) == "atom")
  39. {
  40. context.Response.ContentType = "application/atom+xml";
  41. return new Atom10FeedFormatter(feed);
  42. }
  43. context.Response.ContentType = "application/rss+xml";
  44. return new Rss20FeedFormatter(feed);
  45. }
  46. public bool IsReusable
  47. {
  48. get { return false; }
  49. }
  50. }