asp.net-mvc - ASP.NET MVC Controller 无法使用流式内容正确返回 HttpResponseMessage

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

正如标题所说,我没有让 MVC Controller 正确返回 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 Controller 得到的:

Incorrect result

在使用 WebApi ApiController 时工作正常

Correct result

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

顺便说一句,我正在使用 MVC 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);
}

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

关于asp.net-mvc - ASP.NET MVC Controller 无法使用流式内容正确返回 HttpResponseMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37964330/

相关文章:

c# - Newtonsoft Json 将字典反序列化为 DataContractJsonSerializer 中的键/值列表

javascript - 我可以使用 jQuery Submit 提交 Razor 表单数据吗

c# - SQL select where但只检查参数是否为真

c# - asp.net MVC 4 - 复选框项目的输出列表,将选择与用户相关联 - 允许稍后显示和编辑

asp.net-mvc - 在模型验证之前获取要执行的过滤器

asp.net-mvc-4 - 将 HttpContext.Current.Session 注入(inject)到拦截器/或在内部拦截器中使用时(mvc4 webapi),HttpContext.Current.Session 为 null

c# - IIS 不异步处理 Web Api 请求

c# - 引用自动创建的对象

c# - 无法通过 JSON-RPC 将 CREATEAWTRANSACTION 发布到比特币核心

asp.net-mvc - ASP.NET MVC - 强类型 View 模型,它属于哪里?