如何在 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 中,我们曾经这样做以获得包含字符串内容的响应:

var response = Request.CreateResponse(HttpStatusCode.Ok);
response.Content = new StringContent("<my json result>", Encoding.UTF8, "application/json");

如何在 ASP.NET 5 / MVC 6 中实现相同的效果而不使用任何内置的 类,如 ObjectResult?

您可以直接写入 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 body。
  • MediaTypeHeaderValue class 用于指定内容类型 header。 (它做了一些验证并有一个 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 and/or JsonResult 的实现。