早期搜尋引擎蜘蛛對動態 URL(含 ?、& 參數)抓取效率低,易陷入無限循環或重複索引。為提升 SEO,需將動態參數轉為靜態化路由格式(如 /rentofficelist/3-0-0-0-0.html),引導蜘蛛高效爬取。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// 租屋列表:/rentofficelist/{AredId}-{PriceId}-{AcreageId}-{SortId}-{SortNum}.html
routes.MapRoute(
name: "RentOfficeList",
url: "rentofficelist/{AredId}-{PriceId}-{AcreageId}-{SortId}-{SortNum}.html",
defaults: new { controller = "Home", action = "RentOfficeList" },
namespaces: new[] { "Mobile.Controllers" }
);
// 預設路由放最後
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
參數說明:
name:路由名稱,供 Url.RouteUrl 反向產生連結。url:URL 模式,參數以 {} 包裹,連字號 - 作為分隔,結尾 .html 模擬靜態頁。defaults:預設控制器/Action。namespaces:限定控制器命名空間,避免同名衝突。使用 Url.Action 搭配 RouteValueDictionary 自動對應路由參數:
@* 預設排序連結 *@
<a href="@Url.Action("RentOfficeList", new RouteValueDictionary
{ { "AredId", 0 }, { "PriceId", 0 }, { "AcreageId", 0 }, { "SortId", 0 }, { "SortNum", 0 } })">
預設排序
</a>
@* 篩選連結範例 *@
<a href="@Url.Action("RentOfficeList", new { AredId = 3, PriceId = 0, AcreageId = 0, SortId = 0, SortNum = 0 })">
區域 3
</a>
輸出 HTML:<a href="/rentofficelist/3-0-0-0-0.html">區域 3</a>
public class HomeController : Controller
{
public ActionResult RentOfficeList(int AredId, int PriceId, int AcreageId, int SortId, int SortNum)
{
// 直接使用參數查詢資料庫
var list = _service.GetOffices(AredId, PriceId, AcreageId, SortId, SortNum);
return View(list);
}
// 通用輔助方法:安全取得路由整數參數
protected int GetRouteInt(string key, int defaultValue = 0)
{
object value;
if (RouteData.Values.TryGetValue(key, out value) && value != null)
{
int result;
return int.TryParse(value.ToString(), out result) ? result : defaultValue;
}
return defaultValue;
}
}
/Home/RentOfficeList?AredId=3&PriceId=0&...https://localhost:3841/rentofficelist/3-0-0-0-0.html<link rel="canonical" href="@Url.RouteUrl("RentOfficeList", new { ... })" />,明確告知搜尋引擎標準網址。Range 或自訂驗證屬性,防止非法數值導致 404/500。[HttpGet("rentofficelist/{AredId}-{PriceId}-{AcreageId}-{SortId}-{SortNum}.html")] 更簡潔。透過 MVC 路由將動態查詢字串轉為靜態化路徑,結合前端連結產生與後端參數繫結,有效解決蜘蛛重複抓取、動態 URL 收錄差等 SEO 難題,是傳統 ASP.NET MVC 專案提升搜尋能見度的關鍵技巧。