Search code examples
asp.net-core-1.0asp.net-routing

Can I add route for controller with parameters?


Can I use route attribute for controller and the attribute has parameters, not only constant string in ASP.NET Core? ex. I want add undermentioned definition controller

 [Route("api/sth/{Id}/sth2/latest/sth3")]
 public class MyController : Controller
 {
    public object Get() 
    {
      return new object();
    }
 }

Solution

  • For sure you can, but that tends to be tricky if you don't plan well.

    Let's assume that your owin Startup class is set to default WebApi routes with app.UseMvc()

    This code below works fine and returns ["value1", "value2"] independent of the value {id}

    curl http://localhost:5000/api/values/135/foo/bar/

    [Route("api/values/{id}/foo/bar")]
    public partial class ValuesController : Controller
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
    

    this works fine as well, returning the specified value in route parameter in this case 135

    curl http://localhost:5000/api/values/135/foo/bar/

    [Route("api/values/{id}/foo/bar")]
    public partial class ValuesController : Controller
    {
        [HttpGet]
        public int GetById(int id)
        {
            return id;
        }
    }
    

    But if you combine those 2 actions in the same controller, it'll return a 500 as there are 2 methods that can respond your request.