Web API 2.2 - OData v4(手动解析Uri +扩展)

时间:2015-03-06 18:51:59

标签: odata asp.net-web-api expand

我有一个带有Get方法的ODataController:

public IHttpActionResult Get(ODataQueryOptions<MyModel> queryOptions) {
  IQueryable<MyModel> models = _Models.AsQueryable(); // _Models Defined in Controller as List<MyModel> and is already populated with nested data for both .LevelOne and .LevelOne.LevelTwo which are two other Lists.

  Uri fullrequest = Request.GetRequestContext().Url.Request.RequestUri; // http://localhost:8080/odata/Root?$expand=LevelOne($expand=LevelTwo)
  Uri serviceroot = new Uri(controller.GetLeftPart(UriPartial.Path).Replace("/Root", "")); // http://localhost:8080/odata
  String metadata = service + "/$metadata"; // http://localhost:8080/odata/$metadata

  IEdmModel model = EdmxReader.Parse(XmlTextReader.Create(metadata));
  ODataUriParser parser = new ODataUriParser(model, serviceroot, fullrequest);
  SelectExpandClause selectAndExpand = parser.ParseSelectAndExpand();

//Only one of the two below lines is ever commented in...
  Request.ODataProperties().SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause; // This line will work
  Request.ODataProperties().SelectExpandClause = selectAndExpand; // This line will not work

  return Ok(models);
}

使用我手动解析的selectAndExpand不会扩展数据集,但可以使用预定义的queryOptions。有什么想法吗?在调试器中查看时,两个对象似乎都包含相同的信息,但我必须遗漏一些东西。我希望能够自己解析URI,而根本不需要ODataQueryOptions。

1 个答案:

答案 0 :(得分:2)

我最终要做的是,根据原始请求构建一个新的ODataQueryOptions对象,然后从中拉出SelectExpandClause。它没有回答我的初始问题,但它是一个有点工作的解决方案,不必传递ODataQueryOptions参数。请参阅下面的代码:

public IHttpActionResult Get() {
//Get Queryable Item (in this case just a list made queryable)
  IQueryable<MyModel> models = _Models.AsQueryable();

//Create new ODataQueryContext based off initial request (required to create ODataQueryOptions)
  ODataQueryContext selectAndExpandContext = new ODataQueryContext(Request.ODataProperties().Model, typeof(MyModel), Request.ODataProperties().Path);

//Create new ODataQueryOptions based off new context and original request
  ODataQueryOptions<Employee> selectAndExpandOptions = new ODataQueryOptions<Employee>(selectAndExpandContext, Request);

//Attach Select + Expand options to be processed
  if (selectAndExpandOptions.SelectExpand != null) {
    Request.ODataProperties().SelectExpandClause = selectAndExpandOptions.SelectExpand.SelectExpandClause;
  }

  return Ok(models);
}