Skip to content

Instantly share code, notes, and snippets.

@vvreutskiy
Created April 17, 2016 08:51
Show Gist options
  • Save vvreutskiy/c333336a37238c86788ee631d8e1534f to your computer and use it in GitHub Desktop.
Save vvreutskiy/c333336a37238c86788ee631d8e1534f to your computer and use it in GitHub Desktop.
F# WebApi selfhosted inside LinqPad
<Query Kind="FSharpProgram">
<NuGetReference>Microsoft.AspNet.WebApi.SelfHost</NuGetReference>
</Query>
type ResponseRecord = {value: int; message: string}
type ResponseDiscriminatedUnion =
| Even of ResponseRecord
| Odd of (int * string)
let getResponse i =
match i % 2 with
| 0 -> Even { value = i; message = "even number"}
| 1 -> Odd (i, "odd number")
type SyncController() =
inherit System.Web.Http.ApiController ()
member x.Get (id:int) =
getResponse id
type AsyncController()=
inherit System.Web.Http.ApiController ()
member x.Get (id:int) =
async {
return getResponse id
} |> Async.StartAsTask
type ApiRoute = {id : obj; Controller: string}
let ConfigureHost address =
let conf = new System.Web.Http.SelfHost.HttpSelfHostConfiguration(new Uri(address))
let defaults = { id = System.Web.Http.RouteParameter.Optional; Controller = "Async"}
System.Web.Http.HttpRouteCollectionExtensions.MapHttpRoute (conf.Routes, "DefaultApi", "api/{controller}/{id}", defaults) |> ignore
conf.Formatters.Remove conf.Formatters.XmlFormatter |> ignore
conf.Formatters.JsonFormatter.SerializerSettings.Formatting <- Newtonsoft.Json.Formatting.Indented
conf.Formatters.JsonFormatter.SerializerSettings.Converters.Add (new Newtonsoft.Json.Converters.DiscriminatedUnionConverter()) |> ignore
conf.Formatters.JsonFormatter.SerializerSettings.Converters.Add (new Newtonsoft.Json.Converters.StringEnumConverter()) |> ignore
conf.Formatters.JsonFormatter.SerializerSettings.ContractResolver <- Newtonsoft.Json.Serialization.DefaultContractResolver()
conf
let server = new System.Web.Http.SelfHost.HttpSelfHostServer (ConfigureHost "http://localhost:8090")
let a = server.OpenAsync() |> Async.AwaitTask |> Async.RunSynchronously
printfn "WebApi server started. Cancel all threads and reset (Ctrl+Shift+F5) before restart."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment