使用F#開發ASP.NET Core應用程序


.NET Core 里的F#

在.NET Core剛發布時,就已經添加了對F#的支持。但因為當時F#組件還不完整,而一些依賴包並沒有放在Nuget上,而是社區自己放到MyGet上,所以在使用dotnet new -l fs創建F#模板時需要在項目中自己添加NuGet.config文件以配置依賴包才能還原成功。

不過在1.0.1發布后改善了F#的模板,通過dotnet new創建F#項目已經不需要自己添加NuGet配置了。
使用dotnet new -l fs生成一個控制台應用程序:

在ASP.NET Core中使用F#

在使用dotnet new創建的C#項目中,可以選擇web項目。但F#卻只有ConsoleLib類型,沒有web類型!

既然沒有,那我們就將C#的web項目翻譯成F#的項目。原始項目為用VS 2015創建的不包含驗證的ASP.NET Core項目。

修改project.json文件

通過F#項目的project.json文件,我們可以發現需要修改以下幾個地方。

dependencies節點增加F#的核心組件:

"Microsoft.FSharp.Core.netcore": "1.0.0-*"

在tools節點增加F#的編譯工具:

"dotnet-compile-fsc": "1.0.0-*"

現在這些都還處於預覽版的階段,希望到時正式版時會提供F#的Web模板。

F#有一個比較麻煩的地方就是編譯是按文件順序的,如果在Visual Studio中,可以方便的在解決方案管理窗口里進行文件順序變更。但在.NET Core項目中,則需要在project.json中指定。

buildOptions節點中,增加compilerNamefsc,添加compile節點,includeFiles指定所有需要編譯的文件,最后的buildOptions節點如下:

"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "compilerName": "fsc",
    "compile": {
      "includeFiles": [
        "Controllers/HomeControllers.fs",
        "Startup.fs",
        "Program.fs"
      ]
    }
  },

想了解project.json文件的作用,可以查看 "project.json reference" 。也可以參考博客園里的文章《project.json 這葫蘆里賣的什么葯》

源代碼

修改完project.json文件,接下來將幾個c#文件翻譯成F#即可。這就不細說了,直接把代碼貼上了。
Controllers/HomeControllers.fs

type HomeController() = 
    inherit Controller()

    member this.Index() = this.View()

    member this.About() =
        this.ViewData.["Message"] <- "Your application description page."
        this.View()

    member this.Contact() =
        this.ViewData.["Message"] <- "Your contact page.";
        this.View()

    member this.Error() = this.View()

Startup.fs

type Startup(env: IHostingEnvironment) =
    
    let builder = ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", true, true)
                    .AddJsonFile((sprintf "appsettings.%s.json" env.EnvironmentName), true)
                    .AddEnvironmentVariables();

    let configuration = builder.Build();    

    member this.ConfigureServices(services: IServiceCollection) =
        services.AddMvc() |> ignore


    member this.Configure(app:IApplicationBuilder, env:IHostingEnvironment,loggerFactory: ILoggerFactory) =
        loggerFactory
            .AddConsole(configuration.GetSection("Logging"))
            .AddDebug() 
            |> ignore

        if env.IsDevelopment() then
            app.UseDeveloperExceptionPage()
               .UseBrowserLink()
               |> ignore
        else
            app.UseExceptionHandler("/Home/Error") |> ignore

        app.UseStaticFiles() |> ignore

        app.UseMvc(fun routes -> routes.MapRoute("default","{controller=Home}/{action=Index}/{id?}") |> ignore)
        |>ignore

Program.fs

[<EntryPoint>]
let main argv =    

    let host = WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .Build()

    host.Run()
    0

完整的代碼在此:https://github.com/lhysrc/fs-aspnetcore-demo,有興趣的同學可以下載試試。

記得如果添加了F#源代碼文件,需要將文件路徑添加到project.json - buildOptions - includeFiles中。

結語

雖然可以用,但現在用F#進行ASP.NET Core的開發體驗還不是很好。但只要.NET Core支持F#,相信這些工具方面的應該很快就會跟上。

當我把這個demo傳上github,我發現其實已經有F#的ASP.NET Core模板了。😭不過是基於yo的,,項目地址:https://github.com/OmniSharp/generator-aspnet


本文發表於博客園。 轉載請注明源鏈接:http://www.cnblogs.com/hjklin/p/fs-aspnetcore.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM