Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Controller cannot return HttpResponseMessage correctly with streamed content

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;
    }

This is what I got using MVC Controller:

Incorrect result

It works fine when using WebApi ApiController

Correct result

Correct me if I'm wrong I think the problem is MVC is serializing HttpResponseMessage instead of returning it.

By the way I am using MVC 5.

Thanks in advance.

EDIT I would like to have the flexibility to write to the response stream directly when returning large datasets.

like image 744
superfly71 Avatar asked Sep 20 '26 08:09

superfly71


1 Answers

Perhaps try returning an ActionResult from your MVC method instead.

public ActionResult GetDataAsJsonStream() {}

In order to return a stream, you'll likely have to use FileStreamResult. What would be even easier is just returning a JsonResult.

public ActionResult GetDataAsJson()
{
    object returnObj = new
    {
        Name = "Alice",
        Age = 23,
        Pets = new List<string> { "Fido", "Polly", "Spot" }
    };

    return Json(returnObj, JsonRequestBehavior.AllowGet);
}

This is pseudo code but the concept should be sound.

like image 71
Phil Cooper Avatar answered Sep 22 '26 01:09

Phil Cooper