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

Is it possible to define a parameter before action in url


The question is as simple as the title.

Is it possible to have a route that looks like this: {controller}/{id}/{action}?

This is what I have in code right now (just a simple function) (device is my controller):

[HttpGet]
[Route("Device/{id}/IsValid")]
public bool IsValid(int id) {
    return true;
}

But when I go to the following URL the browser says it can't find the page: localhost/device/2/IsValid.

And when I try this URL, it works just fine: localhost/device/IsValid/2

So, is it possible to use localhost/device/2/IsValid instead of the default route localhost/device/IsValid/2? And how to do this?

Feel free to ask more information! Thanks in advance!


Solution

  • You are using Attribute routing. Make sure you enable attribute routing.

    Attribute Routing in ASP.NET MVC 5

    For MVC RouteConfig.cs

    public class RouteConfig {
    
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapMvcAttributeRoutes();
    
            //...Other code removed for brevity
        }
    }
    

    In controller

    [RoutePrefix("device")]
    public class DeviceController : Controller {
        //GET device/2/isvalid
        [HttpGet]
        [Route("{id:int}/IsValid")]
        public bool IsValid(int id) {
            return true;
        }
    }