John John -4 years ago 90
ASP.NET (C#) Question

Class level Route in asp.net with variable

Is it possible to have a class level

Route
that ends in a variable?
Ex:

[Route("api/{carType}")]
public class CarController : Controller
{
..rest of class
}


and if so how would you access that variable?

Or am I just thinking about this completely wrong? I have a couple of objects that all derive from the same abstract class and right now I have a different controller for each but they are all the same practically. I think it would be possible to have generic methods to handle everything but not sure the best way to interpret what type the object actually is.

Ex:

[Route("api/{carType}")]
public class CarController : Controller
{
[HttpGet()]
public IActionResult GetCars()
{
IActionResult result;
switch(carType){
case "Ford":
result = myService.GetCars<Ford>();
break;
case "Toyota":
result = myService.GetCars<Toyota>();
break;
....
}
return result;
}
}

Answer Source

Yes, you can always do it as in following example:

[RoutePrefix("customers/{customerId}")]
public class OrdersController : ApiController
{
    // GET customers/1/orders
    [Route("orders")]
    public IEnumerable<Order> Get(int customerId) 
    { 
      ... 
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download