动态传递JSON对象对Web API - Newtonsoft例 [英] Passing Dynamic JSON Object to Web API - Newtonsoft Example
问题描述
我需要一个动态的JSON对象传递给我的Web API控制器,这样我可以取决于它是什么类型的处理。我已经使用JSON.NET例如<一试href=\"http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing\">that可以看到这里 但是当我使用小提琴手,我可以看到在JObect通过始终为空。
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"}]}
答这里是我的非常简单的Web API控制器的方法:
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?
可以说,更重要的是,有没有更好的办法在一个动态的JSON对象传递(从JavaScript的AJAX职位)?
Arguably, more importantly, is there a better way to pass in a dynamic JSON object (from an JavaScript AJAX post)?
推荐答案
感谢大家谁在这里帮助。不幸的是,我从来没有对什么是错的底部。
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.
有关信息,我有一个RouteConfig类,它是目前非常简单:
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 }
);
}
}
我的电话到API现在使用JSON.Stringify:
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'
});
原来的API操作工作。
The original API action works.
请注意,我正在与此,此刻所以code只打是不是最好的,但我认为它可能是基本形式是有好处的情况下,别人也有类似的问题。
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.
这篇关于动态传递JSON对象对Web API - Newtonsoft例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!