F# で ASP.NET
F# で ASP.NET を実装してみました。
Visual Web Developer 2010 Express では、F# 用プロジェクトは作成してくれないみたいだったので(Visual F# が要ると思う)、自前で Web.config ファイルを用意し、Visual Web Developer を使わずに実装してみる事にします。
とりあえず、以下をインストールしておきます。
- Visual Web Developer 2010 Express(直接は使わない)
- F# 2.0.0
- F# PowerPack 2.0.0
サンプルソースは http://github.com/fits/try_samples/tree/master/blog/20100906/
設定ファイル Web.confg の用意
Web.config ファイルに以下のような F# コンパイラの設定を行えば、ASP.NET で F# が使用できるようになります。
なお、FSharpAspNetCodeProvider は F# PowerPack に含まれるのでインストールしておく必要があります。
Web.config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" /> </system.web> <system.codedom> <compilers> <compiler language="F#;f#;fs;fsharp" extension=".fs" type="Microsoft.FSharp.Compiler.CodeDom.FSharpAspNetCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809"/> </compilers> </system.codedom> </configuration>
トップページの実装
それでは、ASP.NET のページを作成します。
Language で F# を指定する以外は一般的な ASP.NET のページを作成する事になります。
Default.aspx
<%@ Page Language="F#" AutoEventWireup="true" CodeFile="Default.aspx.fs" Inherits="Fits.Sample.DefaultPage"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>F# Sample</title> </head> <body> <form runat="server"> <div> <asp:TextBox runat="server" id="InfoText" /> <asp:Button runat="server" id="InfoButton" text="Button" onClick="InfoButton_Click" /> </div> <div> <asp:Label runat="server" id="InfoLabel" /> </div> </form> </body> </html>
次に、F# による処理の実装を行います。
自分で配置したコントロール類は、"[
val キーワードはフィールドを初期化無しで宣言するためのもので、DefaultValue 属性でゼロ初期化(今回のケースでは null で初期化)を指定しています。
ちなみに、val キーワードを使って宣言されたフィールドは「明示的なフィールド」と呼ばれます。
Default.aspx.fs
namespace Fits.Sample open System open System.Web open System.Web.UI open System.Web.UI.WebControls type DefaultPage() = inherit Page() [<DefaultValue>] val mutable InfoText : TextBox [<DefaultValue>] val mutable InfoButton : Button [<DefaultValue>] val mutable InfoLabel : Label //ページロード時の処理 member this.Page_Load(sender : obj, e : EventArgs) = this.InfoLabel.Text <- "hello" //ボタンクリック時の処理 member this.InfoButton_Click(sender : obj, e : EventArgs) = this.InfoLabel.Text <- "入力: " + this.InfoText.Text
動作確認
ASP.NET 開発サーバー(通常は C:\Program Files\Common Files\microsoft shared\DevServer\10.0 にインストールされているはず)を使って動作確認を行います。
以下のようにコマンド実行すると、path で指定したディレクトリ内のファイルを ASP.NET で実行します。(path は絶対パスを指定する点に注意)
ASP.NET 開発サーバー実行
>WebDev.WebServer40.exe /port:8080 /path:d:\try_samples\blog\20100906\asp.net_fsharp
上記コマンドの実行後、http://localhost:8080/ に Web ブラウザで接続し、Button ボタンをクリックすると動作している事が確認できるはずです。