ASP.NET MVC控制器无法正确返回带有流内容的HttpResponseMessage [英] ASP.NET MVC Controller cannot return HttpResponseMessage correctly with streamed content
问题描述
正如标题所述,我没有让MVC控制器正确返回HttpResponseMessage.
Just as the title says I am not getting the MVC Controller to return HttpResponseMessage correctly.
[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控制器得到的:
This is what I got using MVC Controller:
在使用WebApi ApiController时工作正常
It works fine when using WebApi ApiController
如果我错了,请纠正我,我认为问题是MVC正在序列化HttpResponseMessage而不是返回它.
Correct me if I'm wrong I think the problem is MVC is serializing HttpResponseMessage instead of returning it.
通过我使用MVC 5的方式.
By the way I am using MVC 5.
谢谢.
编辑 返回大型数据集时,我希望可以灵活地直接写入响应流.
EDIT I would like to have the flexibility to write to the response stream directly when returning large datasets.
推荐答案
感谢Phil,我让MVC控制器返回FileStreamResult使它能够正常工作.
Thanks to Phil I got it to work by having the MVC controller return 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");
}
更新
一种更好的方法是直接写入响应流而无需创建内存流
A better way to do this is to write directly to the response stream without creating a memory stream
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();
}
这篇关于ASP.NET MVC控制器无法正确返回带有流内容的HttpResponseMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!