I need to pass a dynamic JSON object to my Web API controller so that I can process it depending on what type it is. I have tried using the JSON.NET example that can be seen here but when I use Fiddler, I can see that the passed in JObect is always null.
This is an exert from the example pasted into Fiddler:
POST http://localhost:9185/api/Auto/PostSavePage/ HTTP/1.1
User-Agent: Fiddler
Content-type: application/json
Host: localhost
Content-Length: 88
{AlbumName: "Dirty Deeds",Songs:[ { SongName: "Problem Child"},{ SongName:
"Squealer"}]}
Ans here is my very simple Web API controller method:
[HttpPost]
public JObject PostSavePage(JObject jObject)
{
dynamic testObject = jObject;
// other stuff here
}
I am new to this and I have a couple of questions around this area:
Am I doing something wrong in this particular example?
Arguably, more importantly, is there a better way to pass in a dynamic JSON object (from an JavaScript AJAX post)?
As per Perception's comment your JSON doesn't look valid. Run it through JSONLint and you get:
Parse error on line 1:
{ AlbumName: "Dirty De
-----^
Expecting 'STRING', '}'
Change it to have " around the field names:
{
"AlbumName": "Dirty Deeds",
"Songs": [
{
"SongName": "Problem Child"
},
{
"SongName": "Squealer"
}
]
}
Also have you tried swapping out your JObject for either a JToken or a Dynamic object (e.g. here)?
[HttpPost]
public JObject PostSavePage(JToken testObject)
{
// other stuff here
}
OR
[HttpPost]
public JObject PostSavePage(dynamic testObject)
{
// other stuff here
}
Thanks to everyone who helped here. Unfortunately, I never got to the bottom of what was wrong.
I ported the project over piece by piece to a new project and it works fine.
For info, I have a RouteConfig class, which is quite simple at the moment:
public class RouteConfig
{
private static string ControllerAction = "ApiControllerAction";
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: ControllerAction,
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
My call into the API now uses JSON.Stringify:
$.ajax("http://localhost:54997/api/values/PostSavePage/", {
data: JSON.stringify(jObject),
contentType: 'application/json',
type: 'POST'
});
The original API action works.
Note, that I'm only playing with this at the moment so the code is not the best but I thought it may be useful in basic form in case someone else has a similar issue.
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