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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…