Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JsonResult from web api without its properties

Tags:

I have a Web API controller and from there I'm returning an object as JSON from an action.

I'm doing that like this:

public ActionResult GetAllNotificationSettings() {     var result = new List<ListItems>();     // Filling the list with data here...      // Then I return the list     return new JsonResult { Data = result }; } 

But this way the JsonResult object including its Data attribute is serialized as JSON. So my final JSON that is return by the action looks like this:

{     "ContentEncoding": null,     "ContentType": null,     "Data": {         "ListItems": [             {                 "ListId": 2,                 "Name": "John Doe"             },             {                 "ListId": 3,                 "Name": "Jane Doe"             },         ]     },     "JsonRequestBehavior": 1,     "MaxJsonLength": null,     "RecursionLimit": null } 

I can't serialize this JSON string because the JsonResult object added all kinds of other properties to it. I'm only interested in ListItems, nothing else. But it automatically added things like: ContentType, MaxJsonLength etc...

Now this won't work for me because of all the other properties in the JSON string...

var myList = JsonConvert.DeserializeObject<List<ListItems>>(jsonString); 

Is there a way to send a JSON object from the action so that it won't add all the properties that I dont need?

like image 498
Vivendi Avatar asked Aug 20 '14 14:08

Vivendi


People also ask

What does JsonResult return?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

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.


1 Answers

As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!

ActionResult is bad because as you've discovered.

Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.

Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.

public HttpResponseMessage GetAllNotificationSettings() {     var result = new List<ListItems>();     // Filling the list with data here...      // Then I return the list     return Request.CreateResponse(HttpStatusCode.OK, result); } 

In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:

 public class ResponseResultExtractor     {         public T Extract<T>(HttpResponseMessage response)         {             return response.Content.ReadAsAsync<T>().Result;         }     }  var actual = ResponseResultExtractor.Extract<List<ListItems>>(response); 

In this way, you've achieved the below:

  • Your Action can also return Error Messages and status codes like 404 not found so in the above way you can easily handle it.
  • Your Action isn't limited to JSON only but supports JSON depending on the client's request preference and the settings in the Formatter.

Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

like image 147
Dynamic Avatar answered Oct 13 '22 20:10

Dynamic