正如标题所说,我无法正确地让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。
提前致谢。
编辑 我希望有灵活性,在返回大数据集时可以直接写入响应流。
FileStreamResult
。 - Phil Cooper