BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News ASP.NET Core and F# with Giraffe

ASP.NET Core and F# with Giraffe

Giraffe is an F# micro web framework for building web applications. It sits on ASP.NET Core, providing an F# API to the web framework. Giraffe is intended for developers who want to build web applications in F# while retaining access to the features of ASP.NET Core and its ecosystem.

The syntax of Giraffe is similar to Suave, a popular F# web framework. The similarity prompted questions about whether the two frameworks should be either merged or share a common set of APIs. The creator of Giraffe explains why he doesn’t believe merging would add much value:

One of the main differences between Giraffe and Suave is that Giraffe’s fundamental vision, as often stated, is to tightly integrate with ASP.NET Core. It was born to fill the niche where functional .NET devs wanted to build a functional ASP.NET Core web application. Giraffe tries to fill this specific niche by providing a thin layer on top of ASP.NET Core, but keeping the core building blocks of ASP.NET Core alive (DI, HttpRequest, HttpResponse, Config, etc.). This enables F# developers to use a lot of the already existing (and future upcoming) ASP.NET Core ecosystem.

The main building block of Giraffe is HttpHandler. An HttpHandler is a pipeline of functions, similar to ASP.NET Core composition through IApplicationBuilder. The handler can continue the pipeline processing by calling the next handler.

type HttpHandler = HttpFunc -> HttpContext -> HttpFuncResult

Giraffe uses a combinator approach, where HttpHandlers are combined together to create higher level abstractions and ultimately create an application.

let webApp =
choose [
route “/foo” >=> text “Foo”
route “/bar” >=> text “Bar”
]

type Startup() =
member __.Configure (app : IApplicationBuilder)
                    (env : IHostingEnvironment)
                    (loggerFactory : ILoggerFactory) =
    app.UseGiraffe webApp

Giraffe uses .NET Task instead of async workflows, as the two implementations are different and require to convert from each other. Giraffe minimizes conversions that way to reduce overhead.

let personHandler =
    fun (next : HttpFunc) (ctx : HttpContext) ->
        task {
            let! person = ctx.BindModel<Person>()
            return! json person next ctx
        }

Example applications are available on GitHub.

Rate this Article

Adoption
Style

BT