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
?
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.
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.
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 }); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With