OData attribute routing: one controller for multiple data types

2.7k views Asked by At

I am reading the OData V4 update blog: https://blogs.msdn.microsoft.com/webdev/2014/03/13/getting-started-with-asp-net-web-api-2-2-for-odata-v4-0/

It mentions the newly added [ODataRoute] attribute for attribute routing. In the traditional WebApiController, I can specify the routes by using the [Route] attributes for multiple types. For example, say I have two classes Travel and Hotel. I can have one controller for both of them by:

public class DefaultController : WebApiController {
[Route("travel/{id}")]
[Route("hotel/{id}")]
public HttpResponseMessage Get(int id)
{
   // Implementation here
}

With OData stack, each data type is tied to a controller by default, which means I need two controllers:

public class TravelController : ODataController{ }

public class HotelController : ODataController{ }

So is there a way to route multiple data types to one controller with ODataController and ODataRoute? (I tried simply replacing [Route] with [ODataRoute] but it did not work)

1

There are 1 answers

0
Vincent On

You can do like this,

public class MyController :  ODataController

{
    [HttpGet]
    [ODataRoute("Airlines({id})")]
    [ODataRoute("People({id})")]
    public IHttpActionResult Get([FromODataUri] string id)
    {
        return Ok("Empty"+id);
    }
}

I verify this, it works well, and note the controller name is not start from any entity set name.

Also if you do not want to write controller at all, you can refer to this library http://odata.github.io/RESTier/ which will use single predefined controller to handle all requests.