Returning anonymous types using the Web API

Using MVC, returning adhoc Json was easy.

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

I am looking for this functionality using the new web API.

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

This throws an exception because the DataContractJsonSerializer cannot handle anonymous types.

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

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

but I see no reason to use the web API, if I do not return HttpResponseMessage , I would be better off sticking to vanilla MVC. If I try to use:

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

It serializes all HttpResponseMessage .

Can someone lead me to a solution in which I can return anonymous types inside an HttpResponseMessage ?

+55
json c # asp.net-web-api
Apr 12 '12 at 12:15
source share
7 answers

This does not work in beta, but in the last bits (built from http://aspnetwebstack.codeplex.com ), so it will probably become for RC. You can do

 public HttpResponseMessage Get() { return this.Request.CreateResponse( HttpStatusCode.OK, new { Message = "Hello", Value = 123 }); } 
+65
Apr 12 2018-12-12T00:
source share

This answer may be a bit late, but WebApi 2 is out now, and now it's easier to do what you want, you just need to do:

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

and along the pipeline it will be serialized in accordance with xml or json in accordance with the preferences of the client or client ( Accept header). Hope this helps anyone who stumbles upon this question.

+10
Jun 03 '16 at 20:00
source share

you can use JsonObject for this:

 dynamic json = new JsonObject(); json.Message = "Hello"; json.Value = 123; return new HttpResponseMessage<JsonObject>(json); 
+3
May 22 '12 at 10:53
source share

You can use ExandoObject . (add using System.Dynamic; )

 [Route("api/message")] [HttpGet] public object Message() { dynamic expando = new ExpandoObject(); expando.message = "Hello"; expando.message2 = "World"; return expando; } 
+3
Feb 06 '15 at 17:38
source share

You can also try:

 var request = new HttpRequestMessage(HttpMethod.Post, "http://leojh.com"); var requestModel = new {User = "User", Password = "Password"}; request.Content = new ObjectContent(typeof(object), requestModel, new JsonMediaTypeFormatter()); 
+2
Jul 17 '13 at 15:47
source share

You should be able to get this to work if you use generics, as this will give you a “type” for your anonymous type. Then you can bind the serializer to this.

 public HttpResponseMessage<T> MakeResponse(T object, HttpStatusCode code) { return new HttpResponseMessage<T>(object, code); } 

If your class does not have the DataContract or DataMebmer , it will return to serializing all the public properties, which should do exactly what you are looking for.

(I will not be able to check this until a later day, let me know if something is not working.)

+1
Apr 12 2018-12-12T00:
source share

You can encapsulate a dynamic object in a return object, e.g.

 public class GenericResponse : BaseResponse { public dynamic Data { get; set; } } 

and then in WebAPI; do something like:

 [Route("api/MethodReturingDynamicData")] [HttpPost] public HttpResponseMessage MethodReturingDynamicData(RequestDTO request) { HttpResponseMessage response; try { GenericResponse result = new GenericResponse(); dynamic data = new ExpandoObject(); data.Name = "Subodh"; result.Data = data;// OR assign any dynamic data here;// response = Request.CreateResponse<dynamic>(HttpStatusCode.OK, result); } catch (Exception ex) { ApplicationLogger.LogCompleteException(ex, "GetAllListMetadataForApp", "Post"); HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } }; return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError); } return response; } 
0
Apr 04 '16 at 10:36
source share



All Articles