Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi: method to return a simple string

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";
    }
}
like image 771
Old Geezer Avatar asked Dec 03 '22 17:12

Old Geezer


1 Answers

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;
    }
}     
like image 158
twoflower Avatar answered Mar 05 '23 01:03

twoflower