WebSharper - 有一种简单的方法可以捕获"未找到"的路线吗?

boe*_*107 6 f# websharper

是否有一种简单的方法来使用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
Run Code Online (Sandbox Code Playgroud)

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

Tar*_*mil 2

我刚刚发布了一个错误修复(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
    )
Run Code Online (Sandbox Code Playgroud)

请注意,这会捕获所有内容,甚至是文件的 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)
    }
Run Code Online (Sandbox Code Playgroud)

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