Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...