2013-10-24 90 views
4

這是我的問題。我正在使用ASP.NET Web API 2.0和QueryableAttribute來利用一些OData過濾功能。使用OData修改ASP.NET Web API返回的響應內容QueryableAttribute

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

現在,我有一個類,我一直在使用修改響應對象和包含的實體。在開始使用QueryableAttribute之前,這工作正常。在此之前,我從前一個方法而不是IEnumerable返回一個List。

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>> 
    } 
} 

我需要能夠從該得到的實體,我不知道如何從類型得到:

System.Data.Entity.Infrastructure.DbQuery<System.Web.Http.OData.Query.Expressions.SelectExpandBinder.SelectSome<Content.Api.Video>>喜歡的東西List<Video>這樣我就可以修改Video對象。

+0

的未來版本我有OData的完全沒有經驗,所以我可能是完全錯誤的在這裏,但不應該'GetActiveVideos'方法返回'IQueryable

回答

1

取出[Queryable]屬性和管理自己的數據的查詢 - 是這樣的:)

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; 
    }   
} 
+1

一個問題是,從'options.ApplyTo()'返回的對象上調用ToList()將無法編譯。類型參數不能被推斷。 我還不能做到這一點: '變種結果= options.ApplyTo(新GetvContext()Videos.Where(C => c.IsActive)中,s).AsQueryable()鑄

+1

另一個問題是我實際上擴展了QueryableAttribute來解決一些其他的OData特性。 如果我可以得到您的方法的變體工作,如果沒有其他選擇我會使用它,但我真的不希望這樣做,我必須做到這一點,每一個單一的API操作。 –

0

你不能只是做一個ToList( - 中的DBQuery實現IQueryable的...

例如

var content = ((ObjectContent)(response.Content)).Value; 
var queryable = content as IQueryable<Video>; 
var list = queryable.ToList(); 
0

最有可能你是因爲你指定哪些字段應該由你的OData查詢來選擇(例如,$select=Nr,Date)得到這個問題。如果你不這樣做,在應用查詢選項後,OData不會返回SelectSome對象,它將返回與您查詢相同的對象,在您的案例中爲Video。因此,您可以在將它們返回給客戶端之前輕鬆修改這些對象。

如果你需要從Video對象,你並不需要,而不是$select查詢選項排除屬性,你可以使用DTO的,而不是你的Video對象,並在此DTO僅包含那些你需要的字段。

是的,這是一個解決辦法,並希望會有更好的方法做處理服務器端邏輯在這個庫