asp.net-mvc - 锚标记助手链接到 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
参数,该参数应该在解析请求时影响路由的优先级。更改此值不会影响标签助手的输出。
解决方案
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.
推荐阅读
- python - 为什么代码在 Jupyter 中有效而在 Spyder 中无效?
- java - 使用依赖于配置文件中的变量的不同 bean 实现
- java - 使 TestNG 测试依赖于成功完成的测试
- nginx - 阻止对除某些 ip 之外的 nginx url 的访问
- ios - Xcode IB - UILabel 多行文本换行问题 iPhone X + 较新型号
- java - 无法解析字符串符号 AndroidManifest.xml
- ibm-integration-bus - IBM Integration Toolkit (Eclipse) 无法创建新的本地集成节点
- java - 无法使用 Univocity 解析器解析日期
- java - 在请求范围内使用 AspectJ 拦截所有 JDBC 调用并作为响应返回
- ios - 知道在 Realm Collection Change 通知中更改了 Object 的哪个元素?