正如标题所说,我没有让 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 得到的:
在使用 WebApi ApiController 时工作正常
如果我错了请纠正我,我认为问题是 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/