RSS (Really Simple Syndication) 是基於 XML 的內容聚合標準,廣泛用於部落格、新聞網站。網站提供 RSS 輸出,讓使用者透過訂閱工具 (如 Feedly、Inoreader) 無需開啟網頁即可獲取最新內容。
在網站 `
` 區塊加入 link 標籤,告訴瀏覽器與訂閱工具 RSS 位址:<link id="RSSLink" title="RSS" type="application/rss+xml" rel="alternate" href="https://example.com/rss.aspx" />
頁面只保留 Page 指令,移除所有 HTML 標籤:
<%@ Page Language="C#" CodeBehind="Rss.aspx.cs" AutoEventWireup="false" Inherits="MySite.Rss" %>
using System;
using System.Text;
using System.Web;
using System.Xml;
public partial class Rss : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/xml";
Response.Charset = "UTF-8";
var xml = new XmlTextWriter(Response.OutputStream, Encoding.UTF8)
{
Formatting = Formatting.Indented
};
xml.WriteStartDocument();
xml.WriteStartElement("rss");
xml.WriteAttributeString("version", "2.0");
xml.WriteStartElement("channel");
// Channel 基本資訊
xml.WriteElementString("title", "我的部落格");
xml.WriteElementString("link", "https://example.com");
xml.WriteElementString("description", "分享技術心得與生活點滴");
xml.WriteElementString("language", "zh-TW");
xml.WriteElementString("generator", "ASP.NET RSS Generator");
// 動態產生項目
var articles = ArticleService.GetLatest(20);
foreach (var a in articles)
{
xml.WriteStartElement("item");
xml.WriteElementString("title", EncodeXml(a.Title));
xml.WriteElementString("link", a.Url);
xml.WriteElementString("author", a.Author);
xml.WriteElementString("pubDate", a.PublishDate.ToString("R")); // RFC 1123 格式
// Description 使用 CDATA 避免 XML 特殊字元問題
xml.WriteStartElement("description");
xml.WriteCData($"{EncodeXml(a.Summary)}
");
xml.WriteEndElement(); // description
xml.WriteEndElement(); // item
}
xml.WriteEndElement(); // channel
xml.WriteEndElement(); // rss
xml.WriteEndDocument();
xml.Flush();
Response.End();
}
/// XML 特殊字元編碼
private string EncodeXml(string input)
{
if (string.IsNullOrEmpty(input)) return "";
return input
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'");
}
}
atom:link 與 `rel="self"` 以符合最新規範。ASP.NET 實作 RSS 輸出並不複雜,關鍵在於正確的 XML 結構、編碼處理與日期格式。採用 `XmlTextWriter` 或 `SyndicationFeed` 可產生標準相容、易於維護的 RSS 源,提升網站內容觸達率。