Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 644
M Zeinstra Avatar asked Mar 13 '23 20:03

M Zeinstra


2 Answers

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;
    }
}
like image 142
Nkosi Avatar answered Mar 15 '23 10:03

Nkosi


try using this before Default route in RoutingConfig

config.Routes.MapHttpRoute(
    "RouteName",
    "{controller}/{id}/{action}"
    );
like image 42
Imad Avatar answered Mar 15 '23 10:03

Imad