【问题标题】:WebSharper - Is there a simple way to catch "not found" routes?WebSharper - 有没有一种简单的方法来捕捉“未找到”的路线?
【发布时间】:2017-02-01 21:51:21
【问题描述】:

有没有一种简单的方法可以使用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" 之外的任何请求。

【问题讨论】:

    标签: f# websharper


    【解决方案1】:

    我刚刚发布了一个错误修复 (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 这样的 URL 将不再有效。如果您想这样做,则需要使用自定义路由器:

    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 论坛中的回答)

    【讨论】:

    • 谢谢,@Tarmil!我尝试了与您的第一个块完全相同的代码,但它不起作用,但这是在错误修复之前。我要再试一次:-)
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多