4

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();
    }
 }
Art Base
  • 1,739
  • 3
  • 15
  • 23

2 Answers2

4

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.

Tanato
  • 895
  • 12
  • 23
2

You can use RoutePrefix in a fashion similar to this, and then add Routes to each method as required. Parameters defined in the route prefix are still passed to the method in the same way as specifying them in a route on the method.

For example, you could do this:

[RoutePrefix("api/sth/{id}/sth2/latest/sth3")]
public class MyController : ApiController
{
    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3</example>
    [Route()]  // default route, int id is populated by the {id} argument
    public object Get(int id)
    {
    }

    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3/summary</example>
    [HttpGet()]
    [Route("summary")]
    public object GetSummary(int id)
    {
    }

    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3/98765</example>
    [HttpGet()]
    [Route("{linkWith}")]
    public object LinkWith(int id, int linkWith)
    {
    }
}
Craig H
  • 2,001
  • 1
  • 14
  • 18