在Visual Studio .NET 2002剛出來時,我就曾經聽過同事說過他用C++寫過ASP.NET,不過由于當時才剛剛學C#,還不會C++,所以也沒問他是怎么寫的,一直到最近開始學C++,發現在Visual Studio 2005可以用C++/CLI開發Windows Form,但卻無法開發ASP.NET,實在令人遺憾,在網絡上也只在Code Project談到在Visual Studio .NET 2002下用Managed C++寫ASP.NET(ASP.NET with Managed C++),但Managed C++和C++/CLI的語法不太一樣,原本的范例無法compile成功,經過一段研究之后,終于找到了用C++/CLI撰寫ASP.NET的方式。在這篇文章中,我將一步步的demo如何用C++/CLI開發ASP.NET程序。

?

首先,建立一個新的Web Site,由于Visual Studio 2005在ASP.NET沒支持C++,所以建立Web Site時,先隨便選一個語言建立。



建立一個Web Form名為HelloWorld.aspx,請不要選擇Place code in separate file,這樣Visual Studio 2005會將Event Handler放在aspx文件中,可以讓aspx.cpp省掉event宣告的程序。



使用Web Form Designer做出以下的介面。



在Page Directive部分,將Language=”C#”刪除,加上AutoEventWireup="true" Inherits="HelloWorld",HelloWord為C++的Class名稱。也要將<script runat="server"></script>部分刪除。

?1<%@?Page?AutoEventWireup="true"?Inherits="HelloWorld"?%>
?2
?3<!DOCTYPE?html?PUBLIC?"-//W3C//DTD?XHTML?1.0?Transitional//EN"?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
?4<html?xmlns="http://www.w3.org/1999/xhtml">
?5<head?runat="server">
?6??<title>Untitled?Page</title>
?7</head>
?8<body>
?9??<form?id="form1"?runat="server">
10????<div>
11??????Using?C++/CLI?in?ASP.NET<br?/>
12??????<br?/>
13??????<asp:Button?ID="Button1"?runat="server"?OnClick="Button1_Click"?Text="Button"?/>
14??????<asp:Label?ID="Label1"?runat="server"?Text="Label"></asp:Label></div>
15??</form>
16</body>
17</html>
18

建立C++ Project,左側選擇CLR,此為.NET platform的Project,右側選擇CLR Empty Project即可,切記不要選擇Class Library,這樣會多出很多我們不需要的檔案,而且最后我們也不會用Visual Studio 2005來compile,會使用Command Prompt的方式compile。



建立HelloWorld.aspx.cpp。




加入C++/CLI程序。C++/CLI對ANSI C++做了些擴充,為了和C++內建的型別與Class做區別,Managed的Class需加上ref modifier,而Managed的Object要加上^。最重要的,IDE支援Intellisense方式寫ASP.NET。

?1#using?<system.dll>
?2#using?<mscorlib.dll>
?3#using?<system.web.dll>
?4
?5using?namespace?System;
?6using?namespace?System::Web::UI::WebControls;
?7
?8public?ref?class?HelloWorld?:?public?System::Web::UI::Page?{
?9protected:
10??Button^?Button1;
11??Label^??Label1;
12
13public:
14??void?Button1_Click(Object^?sender,?EventArgs^?e)?{
15????this->Label1->Text?=?"Hello?World";
16????return;
17??}

18}
;

使用Visual Studio 2005 Command Prompt編譯C++/CLI。

?

使用以下的語法編譯C++/CLI。

1cl?/clr?HelloWorld.aspx.cpp?/link?/dll?/out:HelloWorld.dll


最后只要將HelloWorld.aspx放到c:\Inetpub\wwwroot\下,HelloWorld.dll放到c:\Inetpub\wwwroot\bin\下,就完成deployment。


結論

很多人說C++無法開發ASP.NET,ANSI C++的確不能,但C++/CLI則可以,事實上,任何.NET下的語言都可以開發ASP.NET,雖然Visual Studio 2005工具不見的支持,但只要透過一些小技巧,你依然可以用妳喜歡的.NET語言開發ASP.NET。


Reference
ASP.NET with Managed C++?, Soliant, The? code project.