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

时间:2016-09-23 23:21:02

标签: 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

我想定义一个EndPoint来处理除"/home""/about"之外的任何请求。

1 个答案:

答案 0 :(得分: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
    )

请注意,这将捕获所有内容,甚至是文件的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论坛的答案中复制)