Reputation: 10113
I'm working on a project in 2017 Visual Studio CE utilizing .Net Core 2.0. I created an API directory for my Web API Controllers, and a Controllers directory for my standard MVC controllers.
I have a StoresController in each directory. The one in the API directory specifies the Route attribute as [Route("api/[controller]")]
. The one in the Controllers directory does not have a Route attribute; it relies on the default routes set up in Startup.cs.
I created the following Delete link on my Edit view using the built-in tag helpers: <a asp-action="Delete" asp-controller="Stores" asp-route-id="@Model.Id" class="btn btn-danger">Delete</a>
For some reason this links to /api/stores/{id} instead of /stores/delete/{id}. Is there a way to configure the tag helpers to use the default MVC routes instead of the API routes? Or do I need to rename classes/action names?
Update: The Route
attribute has an Order
parameter that is supposed to affect the priority of the route when resolving requests. Changing this value did not affect the output of the tag helper.
Upvotes: 2
Views: 704
Reputation: 944
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.
Upvotes: 0
Reputation: 7865
You can add multiple routes to your control with an order, and anchor tag helper with use the first one.
[Route("[controller]/[action]", Order = 0)] // Same as default routes
[Route("api/[controller]/[action]", Order = 1)] // Your custom route
By default, all defined routes have an Order value of 0 and routes are processed from lowest to highest.
Upvotes: 0