Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different route template for controller

Is it possible to change the Routing controller name in MVC? In MVC 5 I would have done this:

[RoutePrefix("MySpecialSauce")]
public class ProductsController : Controller
{
    [Route("GetBy/{id}")]
    public MyObject GetBy(int id)
    {
        return something(id);
    }
}

Now all I can find is to use the default name of your controller:

[Route("[controller]")]
public class ProductsController : Controller
{

    [HttpGet("GetBy/{id}")]
    public MyObject GetBy(int id)
    {
        return something(id);
    }
}

I want to use a different name for my route than actual controller name. How do you do this?

like image 953
Robert Avatar asked Mar 10 '23 11:03

Robert


1 Answers

You can do the same in Core

[Route("MySpecialSauce")]
public class ProductsController : Controller {

    [HttpGet("GetBy/{id:int}")]//Matches GET MySpecialSauce/GetBy/5
    public MyObject GetBy(int id) {
        return something(id);
    }
}

[controller] is a token replacement to help with route template. it is not mandatory.

Source Token replacement in route templates ([controller], [action], [area])

For convenience, attribute routes support token replacement by enclosing a token in square-braces ([, ]). The tokens [action], [area], and [controller] will be replaced with the values of the action name, area name, and controller name from the action where the route is defined.

like image 163
Nkosi Avatar answered Mar 19 '23 12:03

Nkosi