I'm trying to get ASP.NET Core 2 MVC to route the action based on the HTTP verb via the following code in Startup.cs:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "post",
template: "api/{controller}/{id?}",
defaults: new { action = "Post" },
constraints: new RouteValueDictionary(new { httpMethod = new HttpMethodRouteConstraint("POST") })
);
routes.MapRoute(
name: "delete",
template: "api/{controller}/{id?}",
defaults: new { action = "Delete" },
constraints: new RouteValueDictionary(new { httpMethod = new HttpMethodRouteConstraint("DELETE") })
);
routes.MapRoute(
name: "default",
template: "api/{controller}/{action=Get}/{id?}");
});
I.e.,
- If the client calls
GET http://example.com/api/foo
, that runs theGet()
method on myFooController : Controller
class. - If they call
GET http://example.com/api/foo/123
, that runs theGet(int id)
method on myFooController : Controller
class. - If they call
POST http://example.com/api/foo
, that runs thePost([FromBody] T postedItem)
method on myFooController<T> : Controller
class. - If they call
POST http://example.com/api/foo/123
, that runs thePost(int id, [FromBody] T postedItem)
method on myFooController<T> : Controller
class. - If they call
DELETE http://example.com/api/foo/123
, that runs theDelete(int id)
method on myFooController : Controller
When I run the project, it doesn't seem to run any of my controllers. I have some Razor pages that respond but all of the controller-based routes just return 404. Not even the default route seems to work.
I've been using https://github.com/ardalis/AspNetCoreRouteDebugger to try and help me narrow the issue down but I'm still not finding the problem. It shows the methods on the controllers as available actions but doesn't list any of the names, templates or constraints added via MapRoute
. I'd be glad to know of any other helpful tools as well.
FWIW, I'm trying to use the same verb constraints as here: https://github.com/aspnet/Routing/blob/2.0.1/src/Microsoft.AspNetCore.Routing/RequestDelegateRouteBuilderExtensions.cs#L252-L268