问题
I have an entity: ItContract and every ItContract belongs to an organisation unit.
A user logs-in to an organisation unit and have read access to all data. How can I set a filter on organisationUnitId on the server for every odata query?
I am using odata v4 with asp.net.
回答1:
There is a way to override the queryOption you get in 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;
}
来源:https://stackoverflow.com/questions/37339114/add-filter-on-property-for-odata-query