gpt4 book ai didi

f# - WebSharper - 是否有一种简单的方法可以捕获 "not found"路由?

转载 作者:行者123 更新时间:2023-12-04 15:41:04 26 4
gpt4 key购买 nike

有没有简单的使用方法SiteletsApplication.MultiPage生成一种“默认”路由(例如,捕获“未找到”路由)?

例子

type EndPoint =
| [<EndPoint "/">] Home
| [<EndPoint "/about">] About


[<Website>]
let Main =
Application.MultiPage (fun ctx endpoint ->
match endpoint with
| EndPoint.Home -> HomePage ctx
| EndPoint.About -> AboutPage ctx

我想定义一个 EndPoint可以处理除 "/home" 以外的任何请求和 "/about" .

最佳答案

我刚刚发布了一个错误修复(WebSharper 3.6.18),它允许您使用 Wildcard属性:

type EndPoint =
| [<EndPoint "/">] Home
| [<EndPoint "/about">] About
| [<EndPoint "/"; Wildcard>] AnythingElse of string

[<Website>]
let Main =
Application.MultiPage (fun ctx endpoint ->
match endpoint with
| EndPoint.Home -> HomePage ctx
| EndPoint.About -> AboutPage ctx
| EndPoint.AnythingElse path -> Content.NotFound // or anything you want
)

请注意,这将捕获所有内容,甚至文件的 URL,例如,如果您有客户端内容,则 URL 为 /Scripts/WebSharper/*.js将不再工作。如果你想这样做,那么你需要使用自定义路由器:
type EndPoint =
| [<EndPoint "/">] Home
| [<EndPoint "/about">] About
| AnythingElse of string

let Main =
Application.MultiPage (fun ctx endpoint ->
match endpoint with
| EndPoint.Home -> HomePage ctx
| EndPoint.About -> AboutPage ctx
| EndPoint.AnythingElse path -> Content.NotFound // or anything you want
)

[<Website>]
let MainWithFallback =
{ Main with
Router = Router.New
(fun req ->
match Main.Router.Route req with
| Some ep -> Some ep
| None ->
let path = req.Uri.AbsolutePath
if path.StartsWith "/Scripts/" || path.StartsWith "/Content/" then
None
else
Some (EndPoint.AnythingElse path))
(function
| EndPoint.AnythingElse path -> Some (System.Uri(path))
| a -> Main.Router.Link a)
}

(复制自我在 WebSharper 论坛中的回答)

关于f# - WebSharper - 是否有一种简单的方法可以捕获 "not found"路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com