How to create a response message and add content string to it in ASP.NET 5 / MVC 6

Sul Aga picture Sul Aga · Oct 16, 2015 · Viewed 33.5k times · Source

In web api 2 we used to do this to get a response with string content:

var response = Request.CreateResponse(HttpStatusCode.Ok);
response.Content = new StringContent("<my json result>", Encoding.UTF8, "application/json");

How can you acheive the same in ASP.NET 5 / MVC 6 without using any of the built in classes like ObjectResult?

Answer

Daniel J.G. picture Daniel J.G. · Oct 17, 2015

You can write to the Response.Body stream directly (as the Body is a plain old System.IO.Stream) and manually set content type:

public async Task ContentAction()
{
    var jsonString = "{\"foo\":1,\"bar\":false}";
    byte[] data = Encoding.UTF8.GetBytes(jsonString);
    Response.ContentType = "application/json";
    await Response.Body.WriteAsync(data, 0, data.Length);
}

You could save yourself some trouble using some utilities from Microsoft.AspNet.Http:

  • The extension method WriteAsync for writing the string contents into the response body.
  • The MediaTypeHeaderValue class for specifying the content type header. (It does some validations and has an API for adding extra parameters like the charset)

So the same action would look like:

public async Task ContentAction()
{
    var jsonString = "{\"foo\":1,\"bar\":false}";
    Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
    await Response.WriteAsync(jsonString, Encoding.UTF8);
}

In case of doubt you can always have a look at the implementation of ContentResult and/or JsonResult.