Quantcast
Channel: Geekswithblogs.net
Viewing all articles
Browse latest Browse all 6441

Custom MediaType Formatters in MVC 4 Web Api Error: 'Headers.ContentType' must be set before 'ObjectContent' can serialize its content

$
0
0

After upgrading to the MVC 4 Web Api a problem came up where the custom MediaTypeFormatters we were using were no longer functioning.

You must now override, CanWriteType and CanReadType in your customer formatter, or it will return false by default. 

'Headers.ContentType' must be set before 'ObjectContent' can serialize its content"v

Ideally, some checks would be made here to determine if you truly can read or write the type..but for this example, return true.

Throwing the following error:

        /// <summary>
        /// Determines whether this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can serialize an object of the specified type.
        /// </summary>
        /// <param name="type">The type of object that will be serialized.</param>
        /// <returns>
        /// true if this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can serialize an object of that type; otherwise false.
        /// </returns>
        protected override bool CanWriteType(Type type)
        {
            return true;
        }

        /// <summary>
        /// Determines whether this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can deserialize an object of the specified type.
        /// </summary>
        /// <param name="type">The type of object that will be deserialized.</param>
        /// <returns>
        /// true if this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can deserialize an object of that type; otherwise false.
        /// </returns>
        protected override bool CanReadType(Type type)
        {
            return true;
        }

Viewing all articles
Browse latest Browse all 6441

Latest Images

Trending Articles



Latest Images