Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning anonymous types with Web API

When using MVC, returning adhoc Json was easy.

return Json(new { Message = "Hello"}); 

I'm looking for this functionality with the new Web API.

public HttpResponseMessage<object> Test() {        return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK); } 

This throws an exception as the DataContractJsonSerializer can't handle anonymous types.

I have replaced this with this JsonNetFormatter based on Json.Net. This works if I use

 public object Test()  {     return new { Message = "Hello" };  } 

but I don't see the point of using Web API if I'm not returning HttpResponseMessage, I would be better off sticking with vanilla MVC. If I try and use:

public HttpResponseMessage<object> Test() {    return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK); } 

It serializes the whole HttpResponseMessage.

Can anyone guide me to a solution where I can return anonymous types within a HttpResponseMessage?

like image 720
Magpie Avatar asked Apr 12 '12 12:04

Magpie


People also ask

How do I return data from Web API?

Learn the three ways you can return data from your ASP.NET Core Web API action methods. We have three ways to return data and HTTP status codes from an action method in ASP.NET Core. You can return a specific type, return an instance of type IActionResult, or return an instance of type ActionResult.

Can we return view from Web API?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.


2 Answers

This doesn't work in the Beta release, but it does in the latest bits (built from http://aspnetwebstack.codeplex.com), so it will likely be the way for RC. You can do

public HttpResponseMessage Get() {     return this.Request.CreateResponse(         HttpStatusCode.OK,         new { Message = "Hello", Value = 123 }); } 
like image 68
carlosfigueira Avatar answered Oct 09 '22 19:10

carlosfigueira


This answer may come bit late but as of today WebApi 2 is already out and now it is easier to do what you want, you would just have to do:

public object Message() {     return new { Message = "hello" }; } 

and along the pipeline, it will be serialized to xml or json according to client's preferences (the Accept header). Hope this helps anyone stumbling upon this question

like image 45
Luiso Avatar answered Oct 09 '22 19:10

Luiso