2013-0510

ASP.NET MVC Rss订阅实现

作者: momy 分类: 编程开发 0 Comment »
摘要:网站要对外提供资源订阅,自然少不了Rss支持,Rss就是遵循Rss格式的xml文档,网站能自动生成这个自然能方便很多。

网站要对外提供资源订阅,自然少不了Rss支持,Rss就是遵循Rss格式的xml文档,网站能自动生成这个自然能方便很多。

示例:http://www.yn-s.com/Home/Rss


腾讯也提供邮箱订阅功能,前提是你网站要支持rss。


以下是mvc实现此功能代码:

public ActionResult Rss()
        {
                var articles =db.Articles.OrderByDescending(d => d.PubTime).Skip(0).Take(20).ToList();
                XElement contacts = new XElement("rss", new XAttribute("version", "2.0"),
                          new XAttribute(XNamespace.Xmlns + "blogChannel", "http://backend.userland.com/blogChannelModule"),
                           new XAttribute(XNamespace.Xmlns + "dc", "http://purl.org/dc/elements/1.1/"),
                          new XAttribute(XNamespace.Xmlns + "pingback", "http://madskills.com/public/xml/rss/module/pingback/"),
                           new XAttribute(XNamespace.Xmlns + "trackback", "http://madskills.com/public/xml/rss/module/trackback/"),
                           new XAttribute(XNamespace.Xmlns + "wfw", "http://wellformedweb.org/CommentAPI/"),
                           new XAttribute(XNamespace.Xmlns + "slash", "http://purl.org/rss/1.0/modules/slash/"),
                           new XAttribute(XNamespace.Xmlns + "geo", "http://www.w3.org/2003/01/geo/wgs84_pos#"),
                          new XElement("channel",
                               new XElement("title", ViewBag.siteInfo.SiteTitle??""),
                               new XElement("link", Request.Url.Scheme+"://"+Request.Url.Authority),
                               new XElement("description", ViewBag.siteInfo.Description),
                               new XElement("language", "zh_cn"),
                               new XElement("copyright", "Copyright 2011 yn-s.com"),
                               new XElement("webMaster", ViewBag.siteInfo.Email)));
                //这里开始循环写数据
                var category = db.ArticleClass.First().Name;
                foreach (var article in articles)
                {
                    category = db.ArticleClass.First(c => c.ID == article.ArticleClassID).Name;
                    contacts.Element("channel").Add(new XElement("item",
                                     new XElement("title", article.Title),
                                     new XElement("link", "/news/Details/" + article.ID),
                                     new XElement("description", article.Content),
                                     new XElement("category", category),
                                     new XElement("pubDate", article.PubTime)));
                }
                return Content(contacts.ToString(),"text/xml");
        }

说明:以上代码命名空间可以自己根据喜好修改

标签: MVC RSS 资源订阅 阅读: 13920
下一篇: HTML5安全风险详析之一:CORS攻击 - 10572次

向右滑动解锁留言