【问题标题】:Can't generate proper anchor link in .net core 3.0无法在 .net core 3.0 中生成正确的锚链接
【发布时间】:2019-11-22 16:27:40
【问题描述】:

我正在尝试创建一个类似https://localhost:44332/training/course/1/buy 的链接。下面是我生成它的代码:

.cshtml:

<a asp-controller="training"
                   asp-action="course"
                   asp-route-id="1"
                   asp-route-type="buy">Buy now</a>

Startup.cs:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllerRoute(
        name: "Buy",
        pattern: "{controller=Home}/{action=Index}/{id?}/{type=buy}");

    endpoints.MapRazorPages();
});

但它会生成类似https://localhost:44332/training/course/1?type=buy的链接

谁能告诉我,我在哪里做错了?如何生成我期望的链接?

【问题讨论】:

    标签: asp.net-core-mvc asp.net-core-3.0


    【解决方案1】:

    您需要将自定义路由映射放在默认路由映射之前,然后将buy in{type=buy} 替换为{type=test} 之类的其他词,或者只使用{type}

    最终代码:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "Buy",
            pattern: "{controller=Home}/{action=Index}/{id?}/{type=test}");
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
    

    【讨论】:

    • 我做到了,但它显示相同的https://localhost:44332/training/course/1?type=buy
    • @Arif 你是否在默认路由之前更改了自定义路由的顺序?
    • 是的。我变了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多