如何在ASP.NET 5/MVC 6中创建响应消息并向其中添加内容字符串 [英] How to create a response message and add content string to it in ASP.NET 5 / MVC 6

查看:110
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆