ASP.NET Core Route not working

别来无恙 提交于 2019-12-23 10:06:15

问题


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?


回答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.




回答2:


Define the full route, SPA overrides the default MVC routing

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


来源:https://stackoverflow.com/questions/39668039/asp-net-core-route-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!