Anirban
Anirban

Reputation: 589

How to return multiple object type for ApiControllers

I have upgraded my project to use ASP.NET MVC4 from MVC3. Now my controller is using ApiController instead of Controllers. Previously I was using a function as:

 public JsonResult GetPermissions(string portfolioId)
 {
     //DO THE DATA FETCH
     return Json(new { PermissionValues = permissionValues,       UserPermissions = userPermissions, OwnerValues = ownerList },JsonRequestBehavior.AllowGet);
 } 

I would like to do similar operation using ApiControllers. I do not want to create a separate object where the the object will have 3 properties [since I am returning 3 lists]. I was trying to use HttpResponseMessage<Object> as return type of the function but doesn't seem to work though.

    public HttpResponseMessage<Object> GetPermissions(string portfolioId)
    {
      //DO THE DATA FETCH
      HttpResponseMessage<Object> response = new HttpResponseMessage<Object>(new { Users = listedUsers, PermissionValues = permissionValues });
      return response;
    }

Any ideas ?

Upvotes: 2

Views: 6457

Answers (1)

David Peden
David Peden

Reputation: 18434

The primary issue that you have is that the default serializer for json responses in the Beta bits cannot serialize anonymous types. You need to use a formatter that can, such as one based on Json.NET (which will be built-in in the next drop). To make this work with the Beta, your code would change to something like this:

public HttpResponseMessage Get()
{
    var content = new { Users = new List<string> { "John", "Mary" }, Permissions = new List<string> { "User", "Admin" } };
    return new HttpResponseMessage<object>(content, new[] { new JsonNetFormatter() });
}

Which would yield a response like this:

{"Users":["John","Mary"],"Permissions":["User","Admin"]}

Once the RC is available, your existing code should work fine.

Update:

In order for this code to compile, you need an implementation for JsonNetFormatter. You can find an implementation provided by Henrik (MSFT) at http://code.msdn.microsoft.com/Using-JSONNET-with-ASPNET-b2423706#content or from the WebApiContrib project at https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib.Formatting.JsonNet/JsonNetFormatter.cs.

Note, they both suffer from the same bug in the OnWriteToStreamAsync method. Those implementations close the underlying stream. You need to change the using statements to look like this:

using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false })

Henrik noted this in his blog but neither his sample nor the contrib one have been updated and I just haven't had the time to commit the fix to the contrib project. ;)

Upvotes: 1

Related Questions