首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

Visual Studio 自訂 WebForm 專案項目範本:版權標頭、基類繼承與參數替換

     編輯:關於ASP.NET

解決每次新增 WebForm 重複輸入版權宣告、繼承基類、命名空間等樣板代碼。透過複製修改 VS 內建範本,建立個人化 WebForm.zip 範本。

範本來源位置

VS 2008: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\Web\CSharp\2052\WebForm.zip
VS 2005: C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ItemTemplates\Web\CSharp\2052\WebForm.zip

複製一份到工作目錄 (如 D:\MyTemplates\WebForm.zip) 進行修改,原始檔案保留備份。

修改 CodeBehind.cs 範本

// 原始範本內的 CodeBehind.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace $rootnamespace$ {
    public partial class $safeitemname$ : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) { }
    }
}

修改為:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace $rootnamespace$ {
    /// <summary>
    /// $safeitemname$ 頁面
    /// </summary>
    public partial class $safeitemname$ : PageBase {  // 繼承自訂基類
        protected void Page_Load(object sender, EventArgs e) {
            // TODO: 實作頁面邏輯
        }
    }
}

關鍵範本參數說明

修改 WebForm.vstemplate 設定範本屬性

<VSTemplate Version="3.0.0" xmlns="https://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <Name>自訂 WebForm (含 PageBase)

注意:WizardExtension 節點負責解析 $safeitemname$ 等特殊參數,不可刪除,否則產生的類別名會是字面值 $safeitemname$。

安裝自訂範本

  1. 將修改後的 WebForm.zip 放入使用者範本目錄:
    %USERPROFILE%\Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C#\Web\
  2. 重啟 Visual Studio
  3. 專案右鍵 → 新增項目 → 會出現「自訂 WebForm (含 PageBase)」,選擇即可

進階:多檔案範本 (MasterPage + ContentPage)

<TemplateContent>
  <ProjectItem TargetFileName="$fileinputname$.Master">MasterPage.master</ProjectItem>
  <ProjectItem TargetFileName="$fileinputname$.Master.cs">MasterPage.master.cs</ProjectItem>
  <ProjectItem TargetFileName="$fileinputname$.aspx">ContentPage.aspx</ProjectItem>
  <ProjectItem TargetFileName="$fileinputname$.aspx.cs">ContentPage.aspx.cs</ProjectItem>
</TemplateContent>

搭配 WizardExtension 可在新增項目對話框顯示精靈,讓使用者選擇是否建立 MasterPage。

團隊共享範本

  • 將 .zip 放入版控倉庫
  • CI/CD 腳本部署至所有開發機器的使用者範本目錄
  • 或設定 VS Tools → Options → Environment → Projects and Solutions → User project templates location 指向共享網路路徑
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
參數說明範例輸出
$rootnamespace$專案預設命名空間MyProject.Web
$safeitemname$項目名稱 (合法識別碼)UserList
$time$建立時間 (格式視地區設定)2024/01/15 上午 10:30:00
$year$年份2024
$username$登入使用者名稱john.doe