Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying response content returned from ASP.NET Web API using OData QueryableAttribute

Here is my issue. I am using ASP.NET Web API 2.0 and the QueryableAttribute to take advantage of some of the OData filtering functionality.

public class VideoController : ApiController
{
    [HttpGet]
    [Route("activevideos")]
    [Queryable]
    public IEnumerable<Video> GetActiveVideos(ODataQueryOptions<Video> options)
    {
        return new GetvContext().Videos.Where(c => c.IsActive);
    }        
}

Now, I have a class that I have been using to modify the response object and contained entities. This was working fine before I started using the QueryableAttribute. Before this, I was returning a List from the previous method instead of IEnumerable.

public class TestMessageProcessHandler : MessageProcessingHandler
{
    protected override HttpResponseMessage ProcessResponse(
        HttpResponseMessage response, CancellationToken cancellationToken)
    {

        var content = ((ObjectContent)(response.Content)).Value;
        // Do something here with the content.  This used to be a List<Video> 
        // but now the object it is of type: 
        // System.Data.Entity.Infrastructure.DbQuery<System.Web.Http.OData.Query.Expressions.SelectExpandBinder.SelectSome<Content.Api.Video>>
    }
}

I need to be able to get the entity from this and I am not sure how to get from type:

System.Data.Entity.Infrastructure.DbQuery<System.Web.Http.OData.Query.Expressions.SelectExpandBinder.SelectSome<Content.Api.Video>> to something like List<Video> so I can modify the Video object.

like image 736
Brenton House Avatar asked Nov 12 '22 19:11

Brenton House


1 Answers

Remove the [Queryable] attribute and manage the querying of the data yourself - something like this:

public class VideoController : ApiController
{
    [HttpGet]
    [Route("activevideos")]
    public IList<Video> GetActiveVideos(ODataQueryOptions<Video> options)
    {
        var s = new ODataQuerySettings() { PageSize = 1 };
        var result = options.ApplyTo(
            new GetvContext().Videos.Where(c => c.IsActive), s)
            .ToList();

        return result;
    }        
}
like image 168
qujck Avatar answered Nov 15 '22 13:11

qujck