萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 調用 C# COM 組件完整教程:類庫創建、COM 可見、GUID、注冊、ASP 實例化調用

跨語言互操作:ASP (VBScript) 調用 C# 編寫的 COM 組件全流程

將計算密集型邏輯、加密算法、第三方庫調用封裝為 C# COM 組件,供經典 ASP 調用,實現舊系統漸進式現代化。本文涵蓋 Visual Studio 開發、注冊、部署、調用全鏈路。

1. C# 類庫項目創建與配置

  1. VS 中創建 Class Library (.NET Framework) 項目,名稱 MyTestDLL。
  2. 項目屬性 → Build → 勾選 Register for COM interop(需管理員權限運行 VS)。
  3. AssemblyInfo.cs 設置 [assembly: ComVisible(true)]。
  4. 工具 → Generate GUID → 選 Registry Format → 複製 GUID。

2. 接口與類定義(關鍵規範)

using System;
using System.Runtime.InteropServices;

namespace MyTestDll
{
    // 1. 接口名 = I + 類名,需指定 GUID
    [Guid("FFA4B191-FB5B-4dd5-B7B1-B2F32BF6F1FF")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]  // 支持 IDispatch 晚綁定
    public interface IMyTestDll
    {
        [DispId(0)]  // DISPID 必須顯式指定,從 0 或 1 開始
        string GetAbout();
    }

    // 2. 類實現接口,需無參構造函數
    [ClassInterface(ClassInterfaceType.None)]  // 不自動生成類接口,只暴露顯式接口
    [ProgId("MyTestDll.Test1")]  // ProgID,ASP 中 CreateObject 使用
    public class Test1 : IMyTestDll
    {
        private string summary;
        
        public Test1()  // 必須有無參構造函數
        {
            summary = "這是我的第一個測試";
        }
        
        public string GetAbout()
        {
            return summary;
        }
    }
}

3. 編譯與注冊

  • Build 項目,產出 bin\Debug\MyTestDLL.dll 和 .tlb 類型庫。
  • 開發機已自動注冊(勾選 Register for COM interop)。
  • 部署到目標服務器:複製 DLL 到目標路徑(如 C:\ComComponents\MyTestDLL.dll),管理員 CMD 執行:
regasm "C:\ComComponents\MyTestDLL.dll" /tlb:"C:\ComComponents\MyTestDLL.tlb" /codebase

/codebase 允許不在 GAC 中的程序集被 COM 定位,生產環境建議強簽名並安裝 GAC。

4. ASP 調用代碼

<%
Dim obj
On Error Resume Next
Set obj = Server.CreateObject("MyTestDll.Test1")  ' 使用 ProgID
If Err.Number <> 0 Then
    Response.Write "組件創建失敗: " & Err.Description & " (請確認已注冊、位元數匹配、權限足夠)"
    Err.Clear
Else
    Response.Write "組件調用結果: " & obj.GetAbout()
    Set obj = Nothing
End If
%>

5. 位元數匹配陷阱(關鍵)

IIS 應用程序池C# 目標平台結果
Enable 32-Bit Applications = Truex86✅ 正常
Enable 32-Bit Applications = False (默認 64位)x64 / Any CPU (Prefer 32-bit=Off)✅ 正常
Enable 32-Bit Applications = Truex64 / Any CPU (Prefer 32-bit=Off)❌ 800a01ad 無法創建對象
Enable 32-Bit Applications = Falsex86❌ 800a01ad

建議:C# 專案目標平台選 x86,IIS 應用程序池啟用 32 位,最兼容;或雙版本部署(x86/x64 獨立 DLL + 不同 ProgID)。

6. 進階:參數傳遞、數組、對象、事件

' C# 端
[DispId(1)]
int Add(int a, int b) { return a + b; }

[DispId(2)]
string Concat(string[] arr) { return string.Join(",", arr); }

[DispId(3)]
MyData GetData() { return new MyData { Name = "Test", Value = 123 }; }

[ComVisible(true)]
public class MyData { public string Name; public int Value; }
' ASP 端
Response.Write obj.Add(10, 20)  ' 30
Dim arr : arr = Array("a", "b", "c")
Response.Write obj.Concat(arr)  ' a,b,c
Dim data : Set data = obj.GetData()
Response.Write data.Name & "=" & data.Value  ' Test=123

7. 替代方案對比

方案優點缺點適用場景
C# COM 組件強類型、IDE 支持、生態豐富、性能好注冊部署繁瑣、位元數敏感、單機邏輯遷移、加密、圖像處理
Web Service (ASMX/WCF)跨平台、跨語言、標準協議網絡開銷、序列化開銷、配置複雜異構系統集成
HTTP API (ASP.NET Core)RESTful、輕量、容器化友好需重寫客戶端調用新架構、微服務
ActiveX DLL (VB6)原生 ASP 友好、無 .NET 依賴VB6 早已停止支持、難維護極老舊系統維護

COM 互操作是連接經典 ASP 與 .NET 生態的橋樑,用好它能讓遺留系統低成本獲得現代能力。

copyright © 萬盛學電腦網 all rights reserved