asp.net MVC"Action Method"是否可以在不声明参数的特定类型的情况下接收JSON?如果是这样,怎么样?

Jan*_*ray 9 c# asp.net-mvc json

所以,它几乎都在标题中.基本上,我想通过JQuery从客户端向asp.net MVC发送JSON.我想知道它是否有可能接收(但不一定解析)我想从JQuery Ajax调用发送的任何 JSON,无论它是什么类型..没有我具有它的具体类型/模型表示.(基本上像动态类型?)

以常规方式执行此操作(将我声明传递参数作为Object类型)只会带来空值,这正是我所期望的.

基本上,当我收到它时,我想做某种"JSON反射"类型的东西,并且能够通过某种foreach循环等获得它的属性.

提前致谢.任何帮助都会很棒!

Dar*_*rov 10

您可以使用IDictionary<string, object>as action参数.只需编写一个自定义模型绑定器,它将解析JSON请求:

public class DictionaryModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        {
            return null;
        }

        controllerContext.HttpContext.Request.InputStream.Position = 0;
        using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))
        {
            var json = reader.ReadToEnd();
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            return new JavaScriptSerializer().DeserializeObject(json);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将在以下地址注册Application_Start:

ModelBinders.Binders.Add(typeof(IDictionary<string, object>), new DictionaryModelBinder());
Run Code Online (Sandbox Code Playgroud)

然后你可以有以下控制器动作:

[HttpPost]
public ActionResult Foo(IDictionary<string, object> model)
{
    return Json(model);
}
Run Code Online (Sandbox Code Playgroud)

你可以抛出任何东西:

var model = {
    foo: {
        bar: [ 1, 2, 3 ],
        baz: 'some baz value'
    }
};

$.ajax({
    url: '@Url.Action("foo")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(model),
    success: function (result) {
        // TODO: process the results from the server
    }
});
Run Code Online (Sandbox Code Playgroud)