No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In the realm of web APIs, it's common to deal with HTTP requests and responses that need content negotiation—selecting the appropriate media type to handle the data. A prevalent issue that developers may encounter is the error: "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'". This article aims to explore the technical aspects of this error, understand why it occurs, and discuss possible solutions.
Understanding MediaTypeFormatter
MediaTypeFormatter in ASP.NET
In the ASP.NET Web API, MediaTypeFormatter
is an abstract class that handles the serialization and deserialization of HTTP request and response bodies. It helps in mapping between HTTP content types and .NET types. Two commonly used derived classes are:
JsonMediaTypeFormatter: Handlesapplication/json.XmlMediaTypeFormatter: Handlesapplication/xml.
ASP.NET Web API uses these formatters by default to read and write data in JSON or XML. When an unmapped media type like text/plain
is involved, the MediaTypeFormatter might face challenges, leading to errors.
The Problem: MediaTypeFormatter Not Available
When your API controller anticipates receiving or sending data in plain text but lacks the necessary formatter, you'll see the error: "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'". This typically occurs due to the following reasons:
- **No Explicit Formatter for
text/plain**: By default, the Web API may not come configured with a formatter to handletext/plain. - Mismatch in Configuration: It might occur if the API is configured to expect, for example, JSON or XML, but the request uses
text/plain. - Incorrect Request Headers: Improper content-type headers in an HTTP request can trigger this error.
- Type Compatibility: The error may arise if there is an attempt to deserialize the text content directly into complex objects without specifying how.
Solving the Issue
Solution 1: Implementing a Custom MediaTypeFormatter
Create a custom MediaTypeFormatter
for handling text/plain
. Below is a simple way to do it:
- Validation: Always validate the incoming data format with the expected media type.
- Client-Side: Ensure that the client-side code sends the correct media type.
- Robustness: Implement comprehensive error handling to provide meaningful feedback to clients when media type negotiation fails.

