首页 > 解决方案 > 锚标记助手链接到 API 控制器

问题描述

我正在使用 .Net Core 2.0 在 2017 Visual Studio CE 中开发一个项目。我为我的 Web API 控制器创建了一个API目录,并为我的标准 MVC 控制器创建了一个Controllers目录。

我在每个目录中都有一个StoresController 。API目录中的那个将 Route 属性指定为[Route("api/[controller]")]. Controllers目录下的那个没有Route属性;它依赖于Startup.cs中设置的默认路由。

我使用内置标签助手在我的编辑视图上创建了以下删除链接:<a asp-action="Delete" asp-controller="Stores" asp-route-id="@Model.Id" class="btn btn-danger">Delete</a>

由于某种原因,这链接到/api/stores/{id}而不是/stores/delete/{id}。有没有办法将标签助手配置为使用默认的 MVC 路由而不是 API 路由?还是我需要重命名类/动作名称?


更新:Route属性有一个Order参数,该参数应该在解析请求时影响路由的优先级。更改此值不会影响标签助手的输出。

标签: asp.net-mvcasp.net-web-apiasp.net-coreasp.net-core-mvc

解决方案


It's late but for me it was the action names in StoresApiController. If you scaffold an API Controller using Visual Studio targeting .NET Core 2.2 (it might be the same as 2.0), it will generates actions with names that have Stores or Store as suffix:

// this works
public ActionResult GetStores() { ... }
public string GetStore(int id) { ... }
...

But I came from .NET Framework and I used to name my API methods without those suffixes:

// this doesn't work
public ActionResult Get() { ... }
public string Get(int id) { ... }
...

I changed all method names to what Visual Studio would generate for me (GetStores, PostStore, etc). It worked. I'm not sure why. It might be a bug or my little knowledge about routing, but here is the issue on Github.


推荐阅读