> .NET (Core) Web API return content as plain text

Posted on: 2018-03-31 20:30


Whenever I'm working on a WebAPI solution, I always return to the problem on "how to let WebAPI return the content as plain text". The answer to this solution is posted on StackOverflow.

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;

In the code above, a response message is created with which you can specify what kind of content type should be returned.

ASP.NET Core WebAPI is a lot smarter in this regard, because strings are handled as plain text by default:

public IActionResult Get(int id)
    string result = "Hello world! Time is: " + DateTime.Now;
    return Ok(result);