Search code examples
c#asp.net-mvcasp.net-mvc-routing

MVC C# custom Routing


I have a Controller called api, the following

routes.MapRoute(
  name: "api",
  url: "api/",
  defaults: new { controller = "api" }
);

inside the controller I have an action as follows

[Route("fleet/{id:guid}/selectedfleet")]
public ActionResult selectedfleet(Guid id)
{
    return null;
}

the return null is just to test this out, I'm trying to get a breakpoint on it but i am getting url not found, when trying to access something like http://localhost:50593/api/fleet/2df3893d-c406-48fe-8443-1622ddc51af2/selectedfleet


Solution

  • First you need to make sure that if you want to use attribute routing in MVC, that it is enabled.

    public class RouteConfig {
    
        public static void RegisterRoutes(RouteCollection routes) {
    
           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
           routes.MapMvcAttributeRoutes(); //<--IMPORTANT for attribute routing in MVC
    
            // Convention-based routing.
    
            //...other code removed for brevity
        }
    }
    

    when trying to access something like http://localhost:50593/api/fleet/2df3893d-c406-48fe-8443-1622ddc51af2/selectedfleet via attribute routing you need to make sure that the controller has the proper route template defined to match the request.

    [RoutePrefix("api")]
    public class ApiController : Controller {
    
        //GET api/fleet/2df3893d-c406-48fe-8443-1622ddc51af2/selectedfleet
        [HttpGet]
        [Route("fleet/{id:guid}/selectedfleet")]
        public ActionResult selectedfleet(Guid id) { ... }
    }
    

    Make sure that your controller and route does not conflict Web API routes if you have it included in the MVC project.