假设我有一个处理程序从请求中计算一些数据(例如用户 ID),并且该数据由应用程序中的后续代码使用。
我可以想到两种传递这些数据的方法:
1. 变异ctx.Items集合
这看起来像这样:
let authenticate : HttpHandler =
fun (next : HttpFunc) (ctx : HttpContext) ->
task {
printfn "Authenticating... "
let userID = Guid.NewGuid () // Dummy
printfn "Authenticated as %A" userID
ctx.Items.["userID"] <- userID
return! next ctx
}
Run Code Online (Sandbox Code Playgroud)
然后要获取数据,只需执行以下操作:
let showUser : HttpHandler =
fun (next : HttpFunc) (ctx : HttpContext) ->
task {
let userID = ctx.Items.["userID"] :?> Guid
return! text (sprintf "You are authenticated as %A. " userID) next ctx
}
Run Code Online (Sandbox Code Playgroud)
2. 构建一个“包装器”函数(IoC)
这看起来像这样:
let authenticated (innerHandler : Guid -> HttpHandler) : HttpHandler =
fun (next : HttpFunc) (ctx : HttpContext) ->
task {
printfn "Authenticating... "
let userID = Guid.NewGuid () // Dummy
printfn "Authenticated as %A" userID
return! (innerHandler userID) ctx
}
Run Code Online (Sandbox Code Playgroud)
获取数据更容易,而且类型安全!
let showUser (userID : Guid) : HttpHandler =
fun (next : HttpFunc) (ctx : HttpContext) ->
task {
return! text (sprintf "You are authenticated as %A. " userID) next ctx
}
Run Code Online (Sandbox Code Playgroud)
问题