How to declare a parameter as prefix on OData

北城以北 提交于 2019-12-24 14:03:55

问题


Using a normal ApiController in WebApi, I made the following code to define a dynamic map route template for every ApiControllers:

config.Routes.MapHttpRoute(
        name: "Sample",
        routeTemplate: "{sessionId}/{controller}"
     );

I want to achieve a similar behaviour but for every ODataController. I've tried the following code, but it doesn't work:

 config.MapODataServiceRoute(
        routeName: "HSODataRoute",
        routePrefix: "{sessionId}/",
        model: GetEdmModel());

Any idea how this is made in OData? I'm kinda new to it and the internet is lack of information about this.

To be more specific: {sessionId} isn't supposed to be a constant, but a parameter with a Guid value.


回答1:


The ODataConventionModelBuilder by default maps the route /{controller} to the controller whose name is {controller}Controller. E.g. it automatically routes /Products to ProductsController as long as ProductsController derives from ODataController.

If you want more flexibility, you can additionally use routing attributes. E.g.

[ODataRoutePrefix("Products")]
public class Products : ODataController



回答2:


Your following code should work:

config.MapODataServiceRoute(
        routeName: "HSODataRoute",
        routePrefix: "{sessionId}/",
        model: GetEdmModel());

However, you should make sure the request Uri contains only one "/". For example:

I send a Get request as:

http://localhost/{sessionId}/Customers/Default.PrintDate(date=2014-10-24T01:02:03+08:00)

my response is:

{
  "@odata.context":"http://localhost/%7BsessionId%7D/$metadata#Edm.String",
  "value":"10/24/2014 1:02:03 AM +08:00"
}

Where, PrintDate is a custom function bind to collection of customer.

[HttpGet]
public string PrintDate(DateTimeOffset date)
{
    return date.ToString();
}



回答3:


After a few tests I've found out that declaring MapODataServiceRoute is not enough! You need also to add MapHttpRoute also, since ODataController derives from ApiController

config.Routes.MapHttpRoute(
    name: "Sample",
    routeTemplate: "{sessionId}/{controller}"
 );

config.MapODataServiceRoute(
    routeName: "HSODataRoute",
    routePrefix: "{sessionId}/",
    model: GetEdmModel());

I discovered this because after I removed MapHttpRoute, I've started to get 404 not found, and when I added MapHttpRoute the resource could be found.

UPDATE:

The final solution that I've come up to solve this issue was posted here: Pass Parameters in OData WebApi Url.



来源:https://stackoverflow.com/questions/27827188/how-to-declare-a-parameter-as-prefix-on-odata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!