Add filter to property for odata request

I have an object: ItContract, and each ItContract belongs to an organization unit.

The user is registered in the organizational unit and has read access to all data. How can I set a filter on the organizationUnitId on the server for each odata request?

I am using odata v4 with asp.net.

0
source share
1 answer

There is a way to override the queryOption that you get on the server side.

    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;
    }
0
source

All Articles