【问题标题】:ASP.NET MVC Controller cannot return HttpResponseMessage correctly with streamed contentASP.NET MVC 控制器无法使用流式内容正确返回 HttpResponseMessage
【发布时间】:2016-10-24 04:14:51
【问题描述】:

正如标题所说,我没有让 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 控制器得到的:

使用 WebApi ApiController 时效果很好

如果我错了,请纠正我我认为问题是 MVC 正在序列化 HttpResponseMessage 而不是返回它。

顺便说一下,我使用的是 MVC 5。

提前致谢。

编辑 我希望在返回大型数据集时能够灵活地直接写入响应流。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api json.net


    【解决方案1】:

    也许尝试从您的 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);
    }
    

    这是伪代码,但概念应该是合理的。

    【讨论】:

    • 谢谢菲尔。我知道 Json() 控制器方法。我担心的是返回大型数据集时。 Json() 将首先序列化为内存中的 Json 对象,然后再将其写入响应流。我喜欢直接写入流,这样就不会占用内存。
    • @superfly71 如果是这种情况,并且您可能应该在问题中提到它,您可以使用 FileStreamResult 的 contentType 为“application/json”。
    • @superfly71 nice :) 当有人在不久的将来偶然发现这个问题时,这肯定会给出一些背景信息。
    【解决方案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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 2012-08-26
      • 2013-04-01
      • 2023-04-07
      • 2013-07-24
      相关资源
      最近更新 更多