停止在 runtime/handle 路由处执行的函数

Stop functions executing at runtime/handle routing

为 ASP.NET MVC 使用 F# 模板。路由定义了 la

 app.UseRouting()
           .UseEndpoints(fun endpoints ->
                endpoints.MapGet("/", fun context ->
                    context.Response.WriteAsync(PageController.loadHomePage())) |> ignore

                endpoints.MapGet("/contact", fun context ->
                    context.Response.WriteAsync(PageController.loadContactPage())) |> ignore

                endpoints.MapGet("/about", fun context ->
                    context.Response.WriteAsync(PageController.loadAboutPage())) |> ignore

然后是控制器函数,它们都加载同一个页面,并简单地在标题变量中添加子项。 addVariable 函数简单地将“[title]”的所有实例替换为调用 loadTemplate 时提供的字符串。

module PageController

let loadHomePage() =
     Theme.addVariable "title" "Home Page"
     Theme.loadTemplate "index"


let loadContactPage() =
    Theme.loadTemplate "index"

let loadAboutPage() =
    Theme.addVariable "title" "About Us"
    Theme.loadTemplate "index"

然而,当我导航到 /contact 时,它没有定义标题变量,它有一个标题“主页”,这意味着 loadHomePage() 正在 运行 并且设置标题变量。

我是 ASP.NET 和 F# 的新手,所以假设它非常简单。

编辑:

(* Add variable function adds a value to a  dictionary *)
let mutable themeVars = new Dictionary<string, string>()

let addVariable name value =
        themeVars.[name] <- value

(* Load template, opens a file and runs "parseVariables" on the content *)

let ParseVariables (string:string) =
    Regex.Replace(string, "\[(.*?)\]",
        new MatchEvaluator(
            fun matchedVar ->
                let varName = matchedVar.Groups.[1].ToString()
                              |> StringTrim

                if themeVars.ContainsKey varName then
                    themeVars.[varName]
                else
                    "[Undefined Variable: " + varName + "]"
    ))

let loadTemplate templateName =
    if templateExists templateName then
        templateName
        |> getTemplateFilePath
        |> File.ReadAllText
        |> ParseVariables
    else
        "Missing Template: " + templateName + ""

我认为这里的问题是您有一个由所有三个页面共享的可变 themeVars 字典。当您的应用程序启动时,将加载主页,这会将名为 "Title" 的变量添加到字典中。然后,当您访问 Contact 页面时,该变量仍然存在于字典中,无论它的最后一个值是什么。 (可以是 "Home Page""About Us"。)

为避免这种情况,请改为为每个页面创建一个单独的不可变变量查找。像这样:

let loadHomePage() =
    let themeVars = Map [ "Title", "Home Page" ]
    Theme.loadTemplate themeVars "index"

let loadContactPage() =
    let themeVars = Map.empty
    Theme.loadTemplate themeVars "index"

let loadAboutPage() =
    let themeVars = Map [ "Title", "About Us" ]
    Theme.loadTemplate themeVars "index"

请注意,我在这里使用了 Map 而不是 Dictionary,因为它们在 F# 中更容易处理,但两种方式的想法都是相同的。