Search code examples
odataodatalib

Microsoft.Data.OData.ODataMessageWriter using request or response?


The class ODataMessageWriter in Microsoft.Data.OData.dll, v5.6.1.0 accepts constructors that take IODataRequestMessage requestMessage as well as IODataResponseMessage responseMessage. The question is when to use one or the other.

I'm implementing a OData service by hand using ODataMessageWriter, and I'd like to get the headers of my response correct based on the headers in the request... but there seems to require a lot of manual coding to get all the headers right (accept, content-type, DataServiceVersion, etc)... Am I missing something?


Solution

  • If the HTTP message you're writing is a response message (i.e., from the server), then you'll use IODataResponseMessage. If you're constructing a message from a client, you'll use IODataRequestMessage. It sounds like you're writing a server, so you should be using IODataResponseMessage when creating writers and IODataRequestMessage when creating readers.

    You're right that there's a lot of work involved when using ODataLib directly. ODataLib is great when you want/need to write your own server and need a component that knows how to serialize the OData payload format. If you don't need such a high degree of control over your server, I'd recommend using ASP.Net Web API's OData implementation, which actually uses ODataLib under the hood.

    Having said that, ODataLib can figure the Content-Type to respond with if you give it the Accept header from the request. You just need to call SetContentType on the writer settings:

    var settings = new ODataMessageWriterSettings();
    settings.SetContentType(
      "application/json;q=.4, text/html", // Accept
      "iso-8859-5, unicode-1-1;q=0.8"     // Accept-Charset
    );