如何在ASP.NET 5/MVC 6中创建响应消息并向其中添加内容字符串 [英] How to create a response message and add content string to it in ASP.NET 5 / MVC 6
问题描述
在Web api 2中,我们通常这样做是为了获得字符串内容的响应:
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");
如何在不使用ObjectResult之类的内置类的情况下在ASP.NET 5/MVC 6中达到相同的目的?
How can you acheive the same in ASP.NET 5 / MVC 6 without using any of the built in classes like ObjectResult?
推荐答案
您可以直接写入Response.Body
流(因为Body
是普通的System.IO.Stream
)并手动设置内容类型:
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);
}
使用Microsoft.AspNet.Http
中的某些实用程序,您可以省去一些麻烦:
You could save yourself some trouble using some utilities from Microsoft.AspNet.Http
:
- 扩展方法
WriteAsync
将字符串内容写入响应正文. -
MediaTypeHeaderValue
类,用于指定内容类型标题. (它进行了一些验证,并具有用于添加额外的参数(例如字符集)的API)
所以相同的动作看起来像:
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);
}
如有疑问,您可以随时查看 JsonResult
.
In case of doubt you can always have a look at the implementation of ContentResult
and/or JsonResult
.
这篇关于如何在ASP.NET 5/MVC 6中创建响应消息并向其中添加内容字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!