將計算密集型邏輯、加密算法、第三方庫調用封裝為 C# COM 組件,供經典 ASP 調用,實現舊系統漸進式現代化。本文涵蓋 Visual Studio 開發、注冊、部署、調用全鏈路。
MyTestDLL。AssemblyInfo.cs 設置 [assembly: ComVisible(true)]。Registry Format → 複製 GUID。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;
}
}
}
bin\Debug\MyTestDLL.dll 和 .tlb 類型庫。C:\ComComponents\MyTestDLL.dll),管理員 CMD 執行:regasm "C:\ComComponents\MyTestDLL.dll" /tlb:"C:\ComComponents\MyTestDLL.tlb" /codebase
/codebase 允許不在 GAC 中的程序集被 COM 定位,生產環境建議強簽名並安裝 GAC。
<%
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
%>
| IIS 應用程序池 | C# 目標平台 | 結果 |
|---|---|---|
| Enable 32-Bit Applications = True | x86 | ✅ 正常 |
| Enable 32-Bit Applications = False (默認 64位) | x64 / Any CPU (Prefer 32-bit=Off) | ✅ 正常 |
| Enable 32-Bit Applications = True | x64 / Any CPU (Prefer 32-bit=Off) | ❌ 800a01ad 無法創建對象 |
| Enable 32-Bit Applications = False | x86 | ❌ 800a01ad |
建議:C# 專案目標平台選 x86,IIS 應用程序池啟用 32 位,最兼容;或雙版本部署(x86/x64 獨立 DLL + 不同 ProgID)。
' 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
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| C# COM 組件 | 強類型、IDE 支持、生態豐富、性能好 | 注冊部署繁瑣、位元數敏感、單機 | 邏輯遷移、加密、圖像處理 |
| Web Service (ASMX/WCF) | 跨平台、跨語言、標準協議 | 網絡開銷、序列化開銷、配置複雜 | 異構系統集成 |
| HTTP API (ASP.NET Core) | RESTful、輕量、容器化友好 | 需重寫客戶端調用 | 新架構、微服務 |
| ActiveX DLL (VB6) | 原生 ASP 友好、無 .NET 依賴 | VB6 早已停止支持、難維護 | 極老舊系統維護 |
COM 互操作是連接經典 ASP 與 .NET 生態的橋樑,用好它能讓遺留系統低成本獲得現代能力。