26

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sul Aga
  • 6,142
  • 5
  • 25
  • 37

1 Answers1

47

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.

Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
  • Thank you for your answer. What about json formatter settings? can we follow the same pattern as before where we specify the formatter settings in startup class? – Sul Aga Oct 17 '15 at 18:07
  • 1
    Depends on which formatter your use, but if you look at the implementation of JsonResult you will see they use `context.HttpContext.RequestServices.GetRequiredService>()`. This means they allow you to define the options into the built in DI container (possibly in the startup class) and those options will be used in the formatting process. Since you don't want to use the built in `JsonResult`, you could implement something of your own following the same idea. – Daniel J.G. Oct 17 '15 at 18:31
  • you mean I format my json before I use it in writeAsync? of course format it with the settings which I can get from DI – Sul Aga Oct 17 '15 at 18:36
  • 1
    Yep, with `WriteAsync` you are just writing a string (or encoded bytes) directly into the response body. So you would have to create and format the json yourself and then write it into the response body. The likes of `JsonResult` and `ContentResult` are hiding away this process :) – Daniel J.G. Oct 17 '15 at 18:45