为odata查询添加属性过滤器

时间:2016-05-20 06:09:48

标签: odata asp.net-web-api2

我有一个实体:ItContract,每个ItContract都属于一个组织单位。

用户登录组织单位并具有对所有数据的读取权限。 如何为每个odata查询在服务器上的organisationUnitId上设置过滤器?

我在asp.net使用odata v4。

1 个答案:

答案 0 :(得分: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;
    }