0
votes

I have a web api exposing a list of sessions. This is my code :

        [RoutePrefix("api/data")]
        public class SessionController : ApiController
        {
            [HttpGet]
            [Route("sessions")]
            [Queryable]
            public IQueryable<Session> Get()
            {
                List<Session> list = new List<Session>();
                list.Add(new Session { Id = 1, Name = "name 1", Place = "place 1", SessionOn = Convert.ToDateTime("1/1/2014") });
                list.Add(new Session { Id = 2, Name = "name 2", Place = "place 2", SessionOn = Convert.ToDateTime("2/1/2014") });
                list.Add(new Session { Id = 3, Name = "name 3", Place = "place 3", SessionOn = Convert.ToDateTime("3/1/2014") });
                return list.AsQueryable();
            }
        }

        public class Session
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Place { get; set; }
            public DateTime SessionOn { get; set; }
        }

An user can request this api to see all sessions like this :

mydomain/api/data/sessions

I have added the oData to allow user querying and filtering those data like this :

mydomain/api/data/sessions?$filter=Name eq 'name1'
mydomain/api/data/sessions?$filter=Place eq 'place 1'

Everything is working well, the only problem remaining is that I would like to check the query given by the user to tell him that a value is not valid for example :

In my list of sessions, the possible values for the field 'Place' are :

place 1
place 2
place 3
place 4

If the user do the following request :

mydomain/api/data/sessions?$filter=Place eq 'placezzzzz 1'

He will just get an empty sets of Session. What I would like to do, is check in my backend code api the value given (that is to say 'placezzzzz 1') and returns a response to the user telling that this value is invalid.

1
You can check if the backend gives you any data with that query and if nothing, then send an error code backAD.Net
we can return no data if there is really no data for the criteria, but if the criteria is an invalid value I would like to tell it to the useruser2443476

1 Answers

0
votes

You could change your method signature to include a ODataQueryOptions<T> parameter:

[EnableQuery]
public IQueryable<Session> Get(ODataQueryOptions<Session> options) {
    //Do something fun with the filter:
    var filter = options.Filter;
}

The options argument can be added to your Get method without changing the routing. It contains all kinds of info about the request, including the filter that was used. You can still return your IQueryable, just like you are used to.

I use the [System.Web.OData.EnableQuery] attribute instead of [Queryable] because QueryableAttribute is obsolete. (source msdn) I'm not sure this solution will work with the older version.