christopher clark christopher clark - 1 month ago 16
ASP.NET (C#) Question

Route not firing Asp.Net Core

I'm not sure what is wrong with my route. the breakpoint is not firing when I try to access the route.

here is the source message from googles advanced rest client

POST /api/menu HTTP/1.1
HOST: localhost:6223
content-type: application/json
content-length: 34

{ "app_id": 99999, "user_type": 2}


Here is my controller

[Route("api/[controller]")]
public class MenuController : Controller
{
private MenuRepo xMenuRepo;
public MenuController(IOptions<SqlConnectionStringsList> iopt)
{
xMenuRepo = new MenuRepo(iopt);
}

[HttpPost]
public IEnumerable<Menu> GetMenuItems([FromBody] MenuQuery menuq)
{
List<Menu> xMenuList = new List<Menu>();
xMenuList = xMenuRepo.GetMenuItems(menuq.app_id, menuq.user_type);
return xMenuList;
}
}

public class MenuQuery
{
public int app_id { get; set; }
public int user_type { get; set; }
}


I placed a breakpoint on
GetMenuItems
and it is not even firing. The response is a 500 internal server error. This project only has two routes, the default ValuesController with a new project, and this MenuController. I can't find any additional place to specify routes in the project, other than at the top of the controller. But the ValuesController works! I can't figure out what is wrong!?

Answer

Route for action is missing

Routing to Controller Actions: Attribute Routing

Mixed Routing

MVC applications can mix the use of conventional routing and attribute routing. It’s typical to use conventional routes for controllers serving HTML pages for browsers, and attribute routing for controllers serving REST APIs.

Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed. Actions that define attribute routes cannot be reached through the conventional routes and vice-versa. Any route attribute on the controller makes all actions in the controller attribute routed.

[Route("api/[controller]")]
public class MenuController : Controller
{
    private MenuRepo xMenuRepo;
    public MenuController(IOptions<SqlConnectionStringsList> iopt)
    {
        xMenuRepo = new MenuRepo(iopt);
    }

    //POST api/menu
    [HttpPost("")]
    public IEnumerable<Menu> GetMenuItems([FromBody] MenuQuery menuq)
    {
        List<Menu> xMenuList = new List<Menu>();
        xMenuList = xMenuRepo.GetMenuItems(menuq.app_id, menuq.user_type);
        return xMenuList;
    }
}
Comments