搜尋引擎優化 (SEO) 中,`` 直接影響搜尋結果摘要與點擊率。ASP.NET 可在伺服端動態產生並注入此標籤,支援多語系、內容型頁面 (文章、商品) 依資料庫內容自動產生描述。本文示範兩種做法:`HtmlMeta` 控制項與 `Page.MetaDescription` 屬性 (ASP.NET 4.0+)。
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string description = GetMetaDescriptionFromDb(); // 取得動態描述
if (!string.IsNullOrEmpty(description)) {
var meta = new HtmlMeta {
Name = "description",
Content = description
};
Page.Header.Controls.Add(meta);
}
}
}
輸出 HTML:
<meta name="description" content="這是動態產生的頁面描述..." />
protected void Page_Load(object sender, EventArgs e) {
Page.MetaDescription = GetMetaDescriptionFromDb(); // 自動渲染
}
優點:語法簡潔、自動處理 HTML 編碼、避免重複標籤。
private string GetMetaDescriptionFromDb() {
// 假設從資料庫取得原始描述
string raw = ArticleRepository.GetMetaDescription(ArticleId, CurrentCulture);
if (string.IsNullOrWhiteSpace(raw)) return null;
// 限制長度 150-160 字元 (Google 顯示上限)
const int MaxLen = 155;
if (raw.Length > MaxLen) raw = raw.Substring(0, MaxLen).TrimEnd() + "...";
return HttpUtility.HtmlEncode(raw); // 防止雙引號破壞屬性
}
若母版頁已有預設 description,內容頁若再 `Add(HtmlMeta)` 會產生兩個 ``。解決方式:
// 移除現有 description meta
var existing = Page.Header.Controls
.OfType()
.FirstOrDefault(m => m.Name.Equals("description", StringComparison.OrdinalIgnoreCase));
if (existing != null) Page.Header.Controls.Remove(existing);
keywords:`Name="keywords"` (現代 SEO 權重低,可選)robots:`Name="robots", Content="noindex,nofollow"`canonical:使用 `HtmlLink` 設定 `Rel="canonical"`動態掌控 Meta 標籤,讓每頁都有精準、吸引人的搜尋摘要,是 SEO 基礎建設的關鍵一環。