2016-05-20 77 views
0

我有一個實體:ItContract和每個ItContract屬於一個組織單位。添加過濾器的屬性odata查詢

用戶登錄到組織單位並擁有對所有數據的讀取權限。 如何爲每個odata查詢在服務器上的organisationUnitId上設置過濾器?

我正在使用odata v4與asp.net。

回答

0

有一種方法可以覆蓋您在服務器端獲得的queryOption。

public IHttpActionResult Get(ODataQueryOptions<People> queryOptions) 
    {    
     // get the original request before the alterations 
     HttpRequestMessage originalRequest = queryOptions.Request; 

     // get the original URL before the alterations 
     string url = originalRequest.RequestUri.AbsoluteUri; 

     // rebuild the URL 
     if (queryOptions.Filter != null) 
     { 
      // apply the new filter 
      url = url.Replace("$filter=", "$filter=organisationUnitId%20eq%20" + organisationUnitId + ","); 
     } 
     else 
     { 
      if (url.Contains("$")) 
      { 
       url += "&"; 
      } 
      url += "$filter=organisationUnitId%20eq%20" + organisationUnitId; 
     } 

     // build a new request for the filter 
     HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url); 

     // reset the query options with the new request 
     queryOptions = new ODataQueryOptions(queryOptions.Context, req); 
     var result = queryOptions.ApplyTo(_db.Prople); 
     return Ok(result, result.GetType()); 
    } 

    private IHttpActionResult Ok(object content, Type type) 
    { 
     var resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type); 
     return Activator.CreateInstance(resultType, content, this) as IHttpActionResult; 
    }