Geeks With Blogs

News ASP.net Forms Justin Hoffman
Justin Hoffman

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;
        }
Posted on Tuesday, February 28, 2012 3:53 PM | Back to top


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

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Justin Hoffman | Powered by: GeeksWithBlogs.net