4

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!

7
  • You need to change codein RouteConfig file. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{id}/{action}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } Commented Mar 21, 2016 at 11:38
  • @RahulChavan What is th? And where do I have to add it?
    – M Zeinstra
    Commented Mar 21, 2016 at 11:40
  • RouteConfig file in App_start Commented Mar 21, 2016 at 11:40
  • Is this for web api or plain mvc
    – Nkosi
    Commented Mar 21, 2016 at 11:41
  • It can be used for WebAPI as well Commented Mar 21, 2016 at 11:43

2 Answers 2

5

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;
    }
}
2
  • Thanks for your help! :D But, why ":int"? Why should I do that?
    – M Zeinstra
    Commented Mar 21, 2016 at 12:10
  • Its a constraint based on your sample. It could just as easily been bool or long. It's in case you want to make sure types used in the url conforms to the type you want. You don't have to do it. Read the referenced article.
    – Nkosi
    Commented Mar 21, 2016 at 12:11
2

try using this before Default route in RoutingConfig

config.Routes.MapHttpRoute(
    "RouteName",
    "{controller}/{id}/{action}"
    );
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.