【问题标题】:end point not working in .netcore 2.1, why?端点在 .net core 2.1 中不起作用,为什么?
【发布时间】:2020-10-22 22:09:48
【问题描述】:

这是一个关于为什么会发生这种情况的非常简单的问题。

首先,我有一个 .net core 2.1 项目,我需要 3 个额外的端点,所以这是我的代码:

        app.Map("/h1", handle1);
        app.Map("/h1/h2", handle2);
        app.Map("/h1/h3", handle3);

在配置方法中。 handle1、handl2 和 handle3 是在 localhost:port/h1、localhost:port/h1/h2 和 localhost:port/h1/h3 上编写不同内容的自定义方法。

但这不起作用,因为我在 localhost:port/h1/h2 得到的结果与其他两个相同,所以 localhost:port/h1 是正确的,但 localhost:port/h1/h2 和 localhost:port/ h1/h3 显示 localhost:port/h1 这是不正确的。

我已经尝试了一些东西,这是一种工作:

    app.Map("/h1", handle1);
    app.Map("/h/h2", handle2);
    app.Map("/h/h3", handle3);

问题是为什么?以及如何使 localhost:port/h1 和 localhost:port/h1/h2 和 localhost:port/h1/h3 工作?

更新:

我试过了,它有效,但我不明白为什么

    app.Map("/h1/h2", handle2);
    app.Map("/h1/h3", handle3);
    app.Map("/h1", handle1);

【问题讨论】:

    标签: asp.net-core-2.1


    【解决方案1】:

    检查的顺序很重要。

    说你的网址是:

    url = "/h1/h2/somethingcool"
    

    您的地图的构建方式是:

    [ 
      "/h1"
      "/h1/h2",
      "/h1/h3"
    ]
    

    所以当你的地图被循环时会发生这种情况(伪代码):

    for(map.entries() : entry) {
        if(url.startsWith(entry.url) {
           entry.doTheThing(url);
           break;
        }
    }
    

    所以当我们在那里修补值时:

    url = "/h1/h2/somethingcool"
    foreach value in [ "/h1", "/h1/h2", "/h1/h3" ] put it in entry
    loop 1:
       entry = "/h1"
       if([url]"/h1/h2/somethingcool" starts with [entry]"/h1") 
         do the route
         abort looping 
    Loop is aborted
    stopping processing other array items.
    

    现在,如果我们采用您的其他有效地图,我们会得到预期的行为。

    url = "/h1/h2/somethingcool"
    foreach value in [ "/h1/h3", "/h1/h2", "/h1" ] put it in entry
    loop 1:
       entry = "/h1/h3"
       if([url]"/h1/h2/somethingcool" starts with [entry]"/h1/h3") 
         it did not match. Continue looping.
       if([url]"/h1/h2/somethingcool" starts with [entry]"/h1/h2") 
         do the route
         abort looping 
    Loop is aborted
    stopping processing other array items. 
    

    我希望这可以帮助您理解该过程背后的逻辑。这一切都归结为,如果 url 以它开头,而不是完美匹配,则该 url 匹配。

    【讨论】:

    • 这是否意味着 .net 核心错误或背后有原因?
    • @Iria 根据这个答案stackoverflow.com/a/48001921/1356107,这是默认的预期行为。如果只为路径提供了一个字符串,则会检查 url 是否以该路径开头。然后它遍历它的 url 映射并在第一个匹配时停止。先入先出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2021-06-06
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多