blgrnboy
blgrnboy

Reputation: 5157

ASP.NET Core Route not working

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?

Upvotes: 7

Views: 19979

Answers (2)

Rahul Uttarkar
Rahul Uttarkar

Reputation: 3637

Define the full route, SPA overrides the default MVC routing

        [HttpGet("api/[controller]/[action]/{id}")]
        public IActionResult Get(int id)
        {
            return ...;
        }

Upvotes: 2

Huske
Huske

Reputation: 9296

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.

Upvotes: 1

Related Questions