ASP.NET MVC控制器无法正确返回具有流式内容的HttpResponseMessage

3

正如标题所说,我无法正确地让MVC控制器返回HttpResponseMessage。

    [HttpGet]
    [AllowAnonymous]
    public HttpResponseMessage GetDataAsJsonStream()
    {
        object returnObj = new
        {
            Name = "Alice",
            Age = 23,
            Pets = new List<string> { "Fido", "Polly", "Spot" }
        };

        var response = Request.CreateResponse(HttpStatusCode.OK);
        var stream = new MemoryStream().SerializeJson(returnObj);
        stream.Position = 0;
        response.Content = new StreamContent(stream);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return response;
    }

这是我使用MVC控制器得到的结果:

Incorrect result

使用WebApi ApiController时运行良好

Correct result

如果我说错了,请纠正我,我认为问题在于MVC序列化了HttpResponseMessage而不是返回它。
顺便说一下,我正在使用MVC 5。
提前致谢。
编辑 我希望有灵活性,在返回大数据集时可以直接写入响应流。
2个回答

5
也许您可以尝试从MVC方法中返回一个ActionResult
public ActionResult GetDataAsJsonStream() {}

为了返回流,您可能需要使用 FileStreamResult。更简单的方法是返回一个JsonResult
public ActionResult GetDataAsJson()
{
    object returnObj = new
    {
        Name = "Alice",
        Age = 23,
        Pets = new List<string> { "Fido", "Polly", "Spot" }
    };

    return Json(returnObj, JsonRequestBehavior.AllowGet);
}

这只是伪代码,但概念应该是正确的。


谢谢Phil。我知道Json()控制器方法。我关心的是返回大型数据集时。Json()将首先在内存中序列化为Json对象,然后再写入响应流。我喜欢直接写入流,这样就不会占用内存。 - superfly71
@superfly71 如果是这种情况,而且这可能是你在问题中应该提到的内容,你可以使用 contentType 为 'application/json' 的 FileStreamResult - Phil Cooper
@superfly71 不错 :) 这肯定会为那些在不久的将来偶然发现这个问题的人提供一些背景信息。 - Phil Cooper

2
感谢Phil的帮助,我通过MVC控制器返回FileStreamResult使它工作了。
以下是代码:
    public ActionResult GetDataAsJsonStream()
    {
        object returnObj = new
        {
            Name = "Alice",
            Age = 23,
            Pets = new List<string> { "Fido", "Polly", "Spot" }
        };

        var stream = new MemoryStream().SerializeJson(returnObj);
        stream.Position = 0;

        return File(stream, "application/json");
    }

更新

更好的方法是直接写入响应流,而不需要创建内存流。

    public ActionResult GetJsonStreamWrittenToResponseStream()
    {
        object returnObj = new
        {
            Name = "Alice",
            Age = 23,
            Pets = new List<string> { "Fido", "Polly", "Spot" }
        };

        Response.ContentType = "application/json";
        Response.OutputStream.SerializeJson(returnObj);

        return new EmptyResult();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接