【问题标题】:Why does ASP.NET Core ignore asp-action helper tag?为什么 ASP.NET Core 会忽略 asp-action helper 标签?
【发布时间】:2018-05-13 13:32:33
【问题描述】:

我在 Core 2.0 MVC 应用程序中遇到了意外行为。看看这个:

我有一个控制器“ProfileController.cs”,方法很简单:

public async Task<IActionResult> Index()
{
    return View();
}

public async Task<IActionResult> Edit()
{
    return View();
}

我在 Profile/Index.cshtml 中有以下标记:

<a asp-controller="Profile" asp-action="Edit">Edit Profile</a>

我在 Startup.cs 中使用以下路由映射:

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");

但这是我看到的疯狂行为:

锚标签 ALWAYS 无论如何都会生成并导致 profile/index!asp-action="Edit" 被完全忽略,如果 url 上有其他参数,则会导致“index”甚至“index/2”。

为什么?

我知道我的路由工作正常,因为只需输入 /profile/profile/index/profile/edit 即可呈现正确的页面。

【问题讨论】:

  • 这段代码看起来不错。您确定是此代码导致了问题吗?
  • 不,我确信我在其他地方遗漏了一些东西。但无论如何,我没有看到剃须刀引擎如何简单地忽略它给出的动作指令。它一定是在做一些神奇的事情,而不仅仅是应用请求的代码。
  • 我刚刚尝试了与本地项目中相同的代码,它运行良好
  • 我有不同但相似的问题。 asp-action 标签适用于某些方法,但不适用于其他方法。它只是忽略了我的控制器上的 Index() 方法。如果我将它重命名为 IndexLOL() 那么它工作正常。

标签: asp.net-mvc razor asp.net-core asp.net-core-2.0


【解决方案1】:

好的,这是一半的答案。我解决了这个问题,但 Razor 引擎应用了什么魔法仍然是个谜。

我忽略了应用于上述同一 ProfileController 中的 POST 方法的错误路由:

[HttpPost]
[Route("[controller]/Index")]
public async Task<IActionResult> Edit([FromForm]User m)
{
    // do stuff
    return View();
}

注意应用于名为“Edit”的方法的 "/Index" 操作(哎呀!)

删除/修复该路线解决了主要问题:

[HttpPost]
[Route("[controller]/Edit")]
public async Task<IActionResult> Edit([FromForm]User m)
{
    // do stuff
    return View();
}

但它仍然提出了一个问题:为什么 Razor 引擎通过(显然,神奇地)四处嗅探并查看与请求的操作无关的 POST 路由来应用错误的东西? (请记住,在 URL 中输入 /profile/edit 效果很好,尽管我犯了错误,但路由仍然适用于 GET)。

此外,它没有解决当前 url 的参数被应用到路径的问题...

如果我在 /profile/index 上,呈现的动作将是正确的 /profile/index 。但如果我在/profile/Index/2 上,呈现的动作将是错误的/profile/Index/2。我没想到 id 会包含在 action 中。为了纠正这个问题,我必须添加 asp-route-id="" 如下:

<a asp-controller="Profile" asp-action="Index" asp-route-id="">View Profile</a>

这种行为可能是设计使然,但我认为上面的神奇路由问题一定是一个错误。

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多