WebSharper F# 端点 - 捕获所有页面处理程序和页面重定向

3

很抱歉这篇文章有点长。

我正在使用 F# 和 WebSharper(对这两种技术都是新手)。

我定义了一些端点(在添加 NotFound 端点之前我的代码是可用的)。

type EndPoint =
    | [<EndPoint "/">] Home
    | [<EndPoint "/login">] Login
    | [<EndPoint "/about">] About
    | [<EndPoint "/logout">] Logout

    // trying to make a catch-all page handler
    | [<EndPoint "/"; Wildcard>] NotFound of string 
...
let HomePage ctx =
    Templating.Main ctx EndPoint.Home "Home" [
        // page stuff
    ]

let LoginPage ctx =
    Templating.Main ctx EndPoint.Login "Login" [
        h1 [] [text "Login Here"]
        div [] [client <@ Client.LoginWidget() @>]
    ]

// other page constructs
let MissingPage ctx path =
    Templating.Main ctx EndPoint.About "Page Not Found" [
        h1 [] [text "404"]
        p [] [text "The requested page could not be found"]
        p [] [text path]
    ]
...
[<Website>]
let Main =
    Application.MultiPage (fun ctx endpoint ->
        match endpoint with
        | EndPoint.Home -> HomePage ctx
        | EndPoint.About -> AboutPage ctx
        | EndPoint.Login -> LoginPage ctx
        | EndPoint.Logout -> 
            async {
                // call server-side code to log the user out
                // what would i do here to redirect the user to the /login 
                // page
            }
        | EndPoint.NotFound path -> MissingPage ctx path
    )

添加NotFound端点会影响我的其他页面,例如,我的主页开始由MissingPage处理程序处理。我可以理解这一点,因为主页设置为匹配“/”,而未找到模式匹配“/”通配符,尽管我原本希望单个/匹配Home端点,除/Login /About和/Logout之外的任何其他内容都匹配NotFound分支。但显然,我没有正确理解某些东西。
那么,如何获得“catch-all”类型的端点,以便我可以正确处理任何未明确适用的路径?
当我有了NotFound处理代码时,另一件混乱的事情是Login处理程序不再处理。
div [] [client <@ Client.LoginWidget() @>]

最后,在注销处理程序中,我想调用一些服务器端代码(没问题),但是我应该怎么做才能重定向到一个新的网页,例如,将用户发送回/login页面?抱歉再次发这么长的帖子。 Derek
1个回答

3
以下是来自websharper.com的Loïc提供给我的内容,我在这里添加,以防对其他人有所帮助。
首先需要Web.config文件。
<httpErrors errorMode="Custom">
  <remove statusCode="404"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/notfound"/>
</httpErrors>

type EndPoint = 
... other end points
| [<EndPoint "/notfound"; Wildcard>] NotFound of string


[<Website>]
let Main =
    Application.MultiPage (fun ctx endpoint ->
        match endpoint with
        // handle other endpoints
        // Handle none existant paths
        | EndPoint.NotFound _ ->
            // Parse the original URI from ASP.NET's rewrite, in case you need it
            let requestedUri =
                let q = ctx.RequestUri.Query
                let q = q.[q.IndexOf(';') + 1 ..]
                match System.Uri.TryCreate(q, System.UriKind.Absolute) with
                // The request was to /notfound/... directly
                | false, _ -> ctx.RequestUri
                // The request was to a non-existent path, and rewritten by ASP.NET
                | true, uri -> uri

          Content.Text (sprintf "Unknown URI: %A" requestedUri)
          |> Content.SetStatus Http.Status.NotFound

...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接