Is there a way to force ASP.NET Web API to return plain text?

Hmmm… I don’t think you need to create a custom formatter to make this work. Instead return the content like this:

    [HttpGet]
    public HttpResponseMessage HelloWorld()
    {
        string result = "Hello world! Time is: " + DateTime.Now;
        var resp = new HttpResponseMessage(HttpStatusCode.OK);
        resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
        return resp;
    }

This works for me without using a custom formatter.

If you explicitly want to create output and override the default content negotiation based on Accept headers you won’t want to use Request.CreateResponse() because it forces the mime type.

Instead explicitly create a new HttpResponseMessage and assign the content manually. The example above uses StringContent but there are quite a few other content classes available to return data from various .NET data types/structures.

Leave a Comment