2016-10-04 21 views
0

我一直在使用Web API 2和OWIN開發RESTful Web服務。最初我的控制器從ApiController繼承,並且支持GET操作的OData過濾/查詢,即用[EnableQuery]標記。

我們現在決定看看是否可以公開一個真正的OData服務,並使我們的控制器從ODataController而不是ApiController繼承。雖然這似乎大部分運作良好,但$ select不再有效。

public class BaseController : ODataController 
{ 
    ... some properties here, not related to issue... 
} 


public class EmployeesController : BaseController 
{ 
    private readonly AppDbContext _context = new AppDbContext(); 

    [EnableQuery] 
    public IQueryable<Employee> Get() 
    { 
     return _context.Employees; 
    } 
    ... 
} 

我看到的錯誤是:

{ 
    "error": { 
    "code": "", 
    "message": "An error has occurred.", 
    "innererror": { 
     "message": "'DbQuery`1' cannot be serialized using the ODataMediaTypeFormatter.", 
     "type": "System.Runtime.Serialization.SerializationException", 
     "stacktrace": " at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(Type type, Object value, ODataSerializerProvider serializerProvider)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()" 
    } 
    } 
} 

我疑惑這是如何工作與ApiController,但不與ODataController!有什麼我失蹤?

乾杯!

+0

您是否以XML格式請求它? IIRC類型化對象在反序列化時不喜歡「$選擇」。你嘗試一個應用程序/ json來查看這是否是問題。 –

+0

Thanks @MarvinSmit - 我在Postman中發出請求時添加了一個「Accept:application/json」標頭,但我仍然收到相同的錯誤 – Scottie

回答

0

好吧,我想通了,發生了什麼事:

我試圖更新我的OData包爲OData的V4支持最新的版本。 Microsoft .Net OData庫名稱空間在OData v3(System.Web.Http.OData)和v4(System.Web.OData)之間已更改。我以某種方式設法混合這些庫,以便引用舊OData庫中的EnableQuery屬性,從而導致序列化問題。

追蹤不是一個明顯的問題 - 當屬性具有相同的名稱但在不同的命名空間中並且事實上屬於完全不同的版本時,發生什麼情況並不明顯!

相關問題