在Web API 2中,我们曾经这样做来获取字符串内容的响应:
var response = Request.CreateResponse(HttpStatusCode.Ok);
response.Content = new StringContent("<my json result>", Encoding.UTF8, "application/json");
在不使用任何诸如ObjectResult之类的内置类的情况下,如何在ASP.NET 5 / MVC 6中实现相同的目的?
您可以Response.Body
直接写入流(因为原始Body
格式很旧System.IO.Stream
),并手动设置内容类型:
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
:
WriteAsync
用于将字符串内容写入响应主体的扩展方法。MediaTypeHeaderValue
类用于指定内容类型的报头。(它进行了一些验证,并具有用于添加额外的参数(例如字符集)的API)因此,相同的操作如下所示:
public async Task ContentAction()
{
var jsonString = "{\"foo\":1,\"bar\":false}";
Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
await Response.WriteAsync(jsonString, Encoding.UTF8);
}
如有疑问,您可以随时查看ContentResult
和/或的实现JsonResult
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句