ASP.NET Core Route not working

15,562

Solution 1

I think you need to specify controller and not a an action. Your route should be defined as:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "api",
        template: "api/{controller}/{id?}"); <-- Note the change here
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "spa-fallback",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index"});
});

The reason you were getting the results when no parameter was specified was most probably due to the fallback route being called. If you want to know which route is being invoked, have a look at this article on Route Debugging.

Solution 2

Define the full route, SPA overrides the default MVC routing

        [HttpGet("api/[controller]/[action]/{id}")]
        public IActionResult Get(int id)
        {
            return ...;
        }
Share:
15,562
blgrnboy
Author by

blgrnboy

Updated on June 27, 2022

Comments

  • blgrnboy
    blgrnboy almost 2 years

    The Routers are configured this way:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "api",
            template: "api/{action}/{id?}");
    });
    
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "spa-fallback",
            template: "{*url}",
            defaults: new { controller = "Home", action = "Index"});
    });
    

    The controller I action I am trying to request looks like this: // GET api/values/5

    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value" + id;
    }
    

    When I request http://localhost:54057/api/values/get, I get back "value0".

    When I request http://localhost:54057/api/values/get, I get back "value0".

    When I request http://localhost:54057/api/values/get/5, I get back a 404 Not Found.

    Are my routes configured incorrectly, or why is that that the "id" parameter is not passed from the URL to the controller action?