如何在 Suave 用户态中存储数据?
How do I store data in Suave userstate?
我有一个处理 OAuth 回调请求的 Web 部件。
从 API 获取访问令牌和用户 ID 后,我想将其存储在会话状态中。但是当读取后续请求的会话时,我只看到 "Suave.Auth" 键的值。
这是我的 OAuth 回调 Web 部件:
path "/oauth" >=> context (fun ctx ->
let req = ctx.request
match (req.queryParam "code", req.queryParam "error") with
| Choice1Of2 code, _ ->
let id = completeOAuth code
Authentication.authenticated Session false
>=> Writers.setUserData "user-id" id
>=> Redirection.redirect "/view"
| _, Choice1Of2 error -> RequestErrors.UNAUTHORIZED error)
如何确保 "user-id" 值在这个请求之后的其他请求的会话中?
Writers.setUserData
将数据存储在仅在请求期间存在的映射中。
要跨请求存储数据,您需要像这样使用 statefulForSession
。
let app =
statefulForSession >=> context (fun x ->
match HttpContext.state x with
| None ->
// restarted server without keeping the key; set key manually?
let msg = "Server Key, Cookie Serialiser reset, or Cookie Data Corrupt, "
+ "if you refresh the browser page, you'll have gotten a new cookie."
OK msg
| Some store ->
match store.get "counter" with
| Some y ->
store.set "counter" (y + 1) >=> OK (sprintf "Hello %d time(s)" (y + 1))
| None ->
store.set "counter" 1 >=> OK "First time")
我有一个处理 OAuth 回调请求的 Web 部件。
从 API 获取访问令牌和用户 ID 后,我想将其存储在会话状态中。但是当读取后续请求的会话时,我只看到 "Suave.Auth" 键的值。
这是我的 OAuth 回调 Web 部件:
path "/oauth" >=> context (fun ctx ->
let req = ctx.request
match (req.queryParam "code", req.queryParam "error") with
| Choice1Of2 code, _ ->
let id = completeOAuth code
Authentication.authenticated Session false
>=> Writers.setUserData "user-id" id
>=> Redirection.redirect "/view"
| _, Choice1Of2 error -> RequestErrors.UNAUTHORIZED error)
如何确保 "user-id" 值在这个请求之后的其他请求的会话中?
Writers.setUserData
将数据存储在仅在请求期间存在的映射中。
要跨请求存储数据,您需要像这样使用 statefulForSession
。
let app =
statefulForSession >=> context (fun x ->
match HttpContext.state x with
| None ->
// restarted server without keeping the key; set key manually?
let msg = "Server Key, Cookie Serialiser reset, or Cookie Data Corrupt, "
+ "if you refresh the browser page, you'll have gotten a new cookie."
OK msg
| Some store ->
match store.get "counter" with
| Some y ->
store.set "counter" (y + 1) >=> OK (sprintf "Hello %d time(s)" (y + 1))
| None ->
store.set "counter" 1 >=> OK "First time")