0

In the documentation of ODATA's WebAPI there is a page about Attribute Routing.

In this page, there is an example about using ODataRoutePrefixAttribute when all requests to a particular controller have the same prefix, and this prefix can include a parameter. In the sample, all action methods declare the same parameter. From their sample:

[ODataRoutePrefix("Customers({id})")]
public class MyController : ODataController
{
    [ODataRoute("Address")]
    public IHttpActionResult GetAddress(int id)
    {
        ......
    }

    [ODataRoute("Address/City")]
    public IHttpActionResult GetCity(int id)
    {
        ......
    }

    [ODataRoute("/Order")]
    public IHttpActionResult GetOrder(int id)
    {
        ......
    }
}

I would like to avoid repeating the parameter in each and every method and just have it be a property of the class, like this:

[ODataRoutePrefix("Customers({id})")]
public class MyController : ODataController
{
    public int Id
    {
        get { ... }
    }

    [ODataRoute("Address")]
    public IHttpActionResult GetAddress()
    {
        ......
    }
}

How to get the value of the id parameter from the URL when it is not passed as parameter to the action method?

fpintos
  • 151
  • 8

1 Answers1

0

I found out that I could implement the property getter by reading the value from the RequestContext.RouteData.Values:

public string Id => (string)this.RequestContext.RouteData.Values["id"];

One drawback of this solution is that route data values do not seem to be available during the controller's Initialize method, so one needs to be cautious not to depend on such properties in there.

fpintos
  • 151
  • 8