以前生成 RSS 都是使用拼接 Xml 的方式生成的,不仅麻烦而且还不规范。

        #region 输出指定分类编号的消息源内容...

        /// <summary>
/// 输出指定分类编号的消息源内容。
/// </summary>
public void OutputFeed()
{
//int categoryId, string customUrl
int categoryId = 0;
string customUrl = string.Empty;
if (!string.IsNullOrEmpty(RequestUtility.GetQueryString("CategoryId")))
{
categoryId = Convert.ToInt32(RequestUtility.GetQueryString("CategoryId"));
}
if (!string.IsNullOrEmpty(RequestUtility.GetQueryString("Custom")))
{
customUrl = RequestUtility.GetQueryString("Custom");
}
StringBuilder xml = new StringBuilder();
xml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
xml.Append("<rss version=\"2.0\">\n");
xml.Append("<channel>\n");
CategoryInfo category = new CategoryInfo();
if (categoryId == 0 && string.IsNullOrEmpty(customUrl))
{
xml.AppendFormat("<title>{0}</title>\n", string.Format(MemoryCacheProvider.GetLanguage("WebRssTitle", WeilogContext.Current.Application.Prefix), SettingInfo.Name));
}
else if (categoryId == 0 && !string.IsNullOrEmpty(customUrl))
{
category = CategoryService.GetCategory(Provider, customUrl);
xml.AppendFormat("<title>{0}</title>\n", string.Format(MemoryCacheProvider.GetLanguage("WebCategoryRssTitle", WeilogContext.Current.Application.Prefix), category.Name, SettingInfo.Name));
}
else
{
category = CategoryService.GetCategory(Provider, categoryId);
xml.AppendFormat("<title>{0}</title>\n", string.Format(MemoryCacheProvider.GetLanguage("WebCategoryRssTitle", WeilogContext.Current.Application.Prefix), category.Name, SettingInfo.Name));
}
xml.AppendFormat("<link>{0}</link>\n", SettingInfo.Url);
xml.AppendFormat("<description>{0}</description>\n", SettingInfo.Description);
xml.AppendFormat("<language>{0}</language>\n", SettingInfo.Language);// <language>zh-cn</language>
xml.AppendFormat("<copyright>{0}</copyright>\n", "Copyright " + SettingInfo.Name);
xml.AppendFormat("<webMaster>{0}</webMaster>\n", SettingInfo.SmtpMail);
xml.AppendFormat("<generator>{0}</generator>\n", WeilogContext.Current.Application.FullVersion);
xml.Append("<image>\n");
xml.AppendFormat("\t<title>{0}</title>\n", SettingInfo.Name);
xml.AppendFormat("\t<url>{0}</url>\n", "/Common/Images/Logo.jpg");
xml.AppendFormat("\t<link>{0}</link>\n", SettingInfo.Url);
xml.AppendFormat("\t<description>{0}</description>\n", SettingInfo.Description);
xml.Append("</image>\n");
int totalRecords = 0;
List<PostInfo> articleList = new List<PostInfo>();
articleList = PostService.GetPostList(base.Provider, categoryId, null, null, PostType.Post, null, null, null, OrderField.ByPublishTime, OrderType.Desc, 1, 20, out totalRecords);
foreach (PostInfo item in articleList)
{
xml.Append("<item>\n");
xml.AppendFormat("\t<link>{0}</link>\n", string.Format(SitePath.PostLinkFormat, SettingInfo.Url, item.Locator));
xml.AppendFormat("\t<title>{0}</title>\n", item.Title);
xml.AppendFormat("\t<author>{0}</author>\n", item.AuthorName);
xml.AppendFormat("\t<category>{0}</category>\n", CategoryService.GetCategory(Provider, item.CategoryId).Name);
xml.AppendFormat("\t<pubDate>{0}</pubDate>\n", item.PublishTime);
//xml.AppendFormat("\t<guid>{0}</guid>\n", string.Format(WebPath.PostLinkFormat, SettingInfo.Url, item.CustomUrl));
xml.AppendFormat("\t<description>{0}</description>\n", StringUtil.CDATA(string.IsNullOrEmpty(item.Password) ? (SettingInfo.RssType == 0 ? item.Excerpt : item.Content) : MemoryCacheProvider.GetLanguage("MsgEncContent", WeilogContext.Current.Application.Prefix)));
xml.Append("</item>\n");
}
xml.Append("</channel>\n");
xml.Append("</rss>");
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.Write(xml);
} #endregion

前段时间看老外的项目里用到了 SyndicationFeed 这个类来生成 Rss,索性自己做项目的时候也用了一下,果然事半功倍,只需要简洁的代码便可输出 Rss。我的项目是 MVC 的。

        /// <summary>
/// 文章订阅。
/// </summary>
/// <returns>视图的执行结果。</returns>
public ActionResult PostFeed()
{
var feed = new SyndicationFeed(
base.Settings["Name"].ToString(),
base.Settings["Description"].ToString(),
new Uri(Settings["Url"].ToString()),
"BlogRSS",
DateTime.UtcNow); if (!(bool)Settings["Status"])
return new FeedActionResult() { Feed = feed }; var items = new List<SyndicationItem>();
var posts = PostService.GetPostList(Provider, Data.Common.OrderField.ByPublishTime, Data.Common.OrderType.Desc, 20);
foreach (var post in posts)
{
string blogPostUrl = Url.RouteUrl("Post", new { Id = post.Id }, "http");
items.Add(new SyndicationItem(post.Title, post.Content, new Uri(blogPostUrl), String.Format("Blog:{0}", post.Id), post.PublishTime));
}
feed.Items = items;
return new FeedResult() { Feed = feed };
}

FeedResult 是一个自定义的 ActionResult 类:

    /// <summary>
/// 封装一个 RSS 源操作方法的结果并用于代表该操作方法执行框架级操作。
/// </summary>
public class FeedResult : ActionResult
{
/// <summary>
/// 声明 RSS 源对象。
/// </summary>
public SyndicationFeed Feed { get; set; } /// <summary>
/// 初始化 <see cref="FeedResult"/> 类的新实例。
/// </summary>
public FeedResult()
{
} /// <summary>
/// 通过从 System.Web.Mvc.ActionResult 类继承的自定义类型,启用对操作方法结果的处理。
/// </summary>
/// <param name="context">用于执行结果的上下文。 上下文信息包括控制器、HTTP 内容、请求上下文和路由数据。</param>
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/rss+xml"; var rssFormatter = new Rss20FeedFormatter(Feed);
using (var writer = XmlWriter.Create(context.HttpContext.Response.Output))
{
rssFormatter.WriteTo(writer);
}
}
}

最后上一张效果图:

ASP.NET 使用 SyndicationFeed 输出 Rss的更多相关文章

  1. 使用 SyndicationFeed 输出 Rss

    以前生成 RSS 都是使用拼接 Xml 的方式生成的,不仅麻烦而且还不规范. #region 输出指定分类编号的消息源内容... /// <summary> /// 输出指定分类编号的消息 ...

  2. 为ASP.NET MVC视图输出json

    做个小小练习,为asp.net mvc视图输出json字符串: 创建JsonResult操作: 创建此视图: 浏览结果:

  3. asp.net webapi自定义输出结果类似Response.Write()

    asp.net webapi自定义输出结果类似Response.Write()   [HttpGet] public HttpResponseMessage HelloWorld() { string ...

  4. 在 ASP.NET MVC Web 应用程序中输出 RSS Feeds

    RSS全称Really Simple Syndication.一些更新频率较高的网站可以通过RSS让订阅者快速获取更新信息.RSS文档需遵守XML规范的,其中必需包含标题.链接.描述信息,还可以包含发 ...

  5. ASP.Net 更新页面输出缓存的几种方法

    ASP.Net 自带的缓存机制对于提高页面性能有至关重要的作用,另一方面,缓存的使用也会造成信息更新的延迟.如何快速更新缓存数据,有时成了困扰程序员的难题.根据我的使用经验,总结了下面几种方法,概括了 ...

  6. asp,asp.net 以表格输出excel,数据默认科学计数的解决办法

    关键字:  style="vnd.ms-excel.numberformat:@" 问题:在用table仿excel生成中经常遇到类似于身份证的长整数类型excel默认当成科学计数 ...

  7. Asp.Net MVC5 格式化输出时间日期

    刚好用到这个,网上找的全部是输出文本框内容的格式化日期时间 而我需要只是在一个表格中的单元个中输出单纯的文字 最后在MSDN上找到 HtmlHelper.FormatValue 方法 public s ...

  8. ASP.NET中常用输出JS脚本的类(来自于周公博客)

    using System; using System.Collections.Generic; using System.Text; using System.Web; using System.We ...

  9. ASP.NET后台怎么输出方法中间调试信息?

    后台方法,不止是aspx.cs,而是页面调用的一些其它方法.想调试这些方法,我以前winform都是MessageBox.Show一些中间结果,现在我也想用这种方式.但想想,网页会触发 Message ...

随机推荐

  1. Outlook 邮箱脱机工作解决方法

    在运维过程中,有时候会收到用户这样的抱怨:为什么别人发给我的邮件我都收不到,我的邮件也发不出去了? Outlook 2016图标上显示着一个红叉... 这种情况有时候是因为Outlook正在脱机工作, ...

  2. 【Python】Python format 格式化函数(转帖)

    https://www.runoob.com/python/att-string-format.html Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符 ...

  3. 003-结构型-01-适配器模式(Adapter)

    一.概述 将一个类的接口转换成客户期望的另一个接口.适配器模式让那些接口不兼容的类可以一起工作. 1.1.适用场景 已经存在的类,它的方法和需求不匹配时(方法结果相同或相似) 不是软件设计阶段考虑的设 ...

  4. ELK之elasticsearch删除索引

    参考文档:https://www.cnblogs.com/Dev0ps/p/9493576.html elasticsearch使用时间久了会产生大量索引占用磁盘空间,可以删除索引来释放 查看当前所有 ...

  5. 查看某个进程PID对应的文件句柄数量,查看某个进程当前使用的文件句柄数量

    ================================ 1.linux所有句柄查询 lsof -n|awk '{print $2}'|sort|uniq -c |sort -nr|more ...

  6. 使用Apache,压力测试redisson的一般高并发

    安装 Linux linux直接yum -y install httpd-tools,然后ab -V测试 Windows 1查看80端口有没有被占用,netstat -ano | findstr &q ...

  7. c#关于Dictionary中自定义Key

    Dictionary 描述 字典 Dictionary 通过 Hash 桶算法进行O(1)查找数据,在 Hash 碰撞达到一定次数后会自动进行 Resize,也会在数组大小不足的时候会自动进行Resi ...

  8. 遵循统一的机器学习框架理解SVM

    遵循统一的机器学习框架理解SVM 一.前言 我的博客仅记录我的观点和思考过程.欢迎大家指出我思考的盲点,更希望大家能有自己的理解. 本文参考了李宏毅教授讲解SVM的课程和李航大大的统计学习方法. 二. ...

  9. PPM / PGM / PBM 图像文件格式

    PPM / PGM / PBM 图像文件格式 声明:引用请注明出处http://blog.csdn.net/lg1259156776/ 说明:在进行图像压缩后传输,然后解压缩显示的过程中,通常会用到P ...

  10. layuiAdmin (单页版)常见问题与解决方案

    最近项目开发中用到了layuiAdmin的单页版进行开发,期间遇到一些问题,在此总结一二: 单页版缓存问题 由于单页面版本的视图文件和静态资源模块都是动态加载的,所以可能存在浏览器的本地缓存问题,因此 ...