4

One of my methods need to return just a simple string of text. What should be the return type of the method? Do I still declare it in a subclass of ApiController?

I tried the following but it does not work:

public class TestController : ApiController
{
    public string Announcements()
    {
        return "Testing abc";
    }
}
Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • possible duplicate of [Is there a way to force ASP.NET Web API to return plain text?](http://stackoverflow.com/questions/11581697/is-there-a-way-to-force-asp-net-web-api-to-return-plain-text) – Augusto Barreto Feb 15 '15 at 19:35

1 Answers1

18

By default, Web API will send the string as a JSON. However, you can manually force it to return just the text itself and accompany it with the appropriate content type:

public class TestController : ApiController
{
    public HttpResponseMessage Announcements()
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent("Testing abc");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
        return response;
    }
}     
twoflower
  • 6,788
  • 2
  • 33
  • 44