Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 787
Sul Aga Avatar asked Oct 16 '15 20:10

Sul Aga


1 Answers

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.

like image 124
Daniel J.G. Avatar answered Oct 04 '22 02:10

Daniel J.G.