简体   繁体   中英

OData attribute routing: one controller for multiple data types

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM