代码之家  ›  专栏  ›  技术社区  ›  weilin8

在ASP.NET MVC中,在控制器的操作方法之前或中反序列化JSON

  •  20
  • weilin8  · 技术社区  · 17 年前

    { 
        "ID" : 1,
        "FullName" : {
           "FirstName" : "John",
           "LastName" : "Smith"
        }
    }
    

    同时,我在服务器端为这个数据结构编写了类。

    public class User
    {
        public int ID { get; set; }
        public Name FullName { get; set;}
    }
    
    public class Name
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    当我在控制器类中使用以下代码运行网站时,FullName属性不会被反序列化。我做错了什么?

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Submit(User user)
    {
        // At this point, user.FullName is NULL. 
    
        return View();
    }
    
    5 回复  |  直到 17 年前
        1
  •  23
  •   weilin8    17 年前

    我通过实现一个动作过滤器解决了我的问题;下面提供了代码示例。从研究中,我了解到还有另一种解决方案,即模型绑定器 武帕拉 如上所述。但我真的不知道这两种方法的利弊。

    感谢Steve Gentile的 blog post

    public class JsonFilter : ActionFilterAttribute
        {
            public string Parameter { get; set; }
            public Type JsonDataType { get; set; }
    
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
                {
                    string inputContent;
                    using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
                    {
                        inputContent = sr.ReadToEnd();
                    }
    
                    var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
                    filterContext.ActionParameters[Parameter] = result;
                }
            }
        }
    
    [AcceptVerbs(HttpVerbs.Post)]
    [JsonFilter(Parameter="user", JsonDataType=typeof(User))]
    public ActionResult Submit(User user)
    {
        // user object is deserialized properly prior to execution of Submit() function
    
        return View();
    }
    
        2
  •  11
  •   takepara    17 年前

    1.创建自定义模型活页夹

      public class UserModelBinder : IModelBinder
      {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
          User model;
    
          if(controllerContext.RequestContext.HttpContext.Request.AcceptTypes.Contains("application/json"))
          {
            var serializer = new JavaScriptSerializer();
            var form = controllerContext.RequestContext.HttpContext.Request.Form.ToString();
            model = serializer.Deserialize<User>(HttpUtility.UrlDecode(form));
          }
          else
          {
            model = (User)ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
          }
    
          return model;
        }
      }
    

    2.在应用程序启动事件中添加模型绑定器

      ModelBinders.Binders[typeof(User)] = new UserModelBinder();
    

    3.使用jQuery$.get/$.post查看客户端JavaScript代码。

      <% using(Html.BeginForm("JsonData","Home",new{},FormMethod.Post, new{id="jsonform"})) { %>
    
        <% = Html.TextArea("jsonarea","",new {id="jsonarea"}) %><br />
    
        <input type="button" id="getjson" value="Get Json" />
        <input type="button" id="postjson" value="Post Json" />
      <% } %>
      <script type="text/javascript">
        $(function() {
          $('#getjson').click(function() {
            $.get($('#jsonform').attr('action'), function(data) {
              $('#jsonarea').val(data);
            });
          });
    
          $('#postjson').click(function() {
            $.post($('#jsonform').attr('action'), $('#jsonarea').val(), function(data) {
              alert("posted!");
            },"json");
          });
        });
      </script>
    
        3
  •  5
  •   Ryan Taylor    17 年前

    Json.NET . 这个 documentation 非常好,应该可以 do what you need . 您还需要抓取 JsonNetResult 因为它返回一个ActionResult,可以在ASP.NET MVC应用程序中使用。它很容易使用。

    Json.NET还可以很好地处理日期序列化。更多信息 can be found here

        4
  •  5
  •   CmdrTallen    17 年前

    试试这个;

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Submit(FormCollection collection)
    {
        User submittedUser = JsonConvert.DeserializeObject<User>(collection["user"]); 
        return View();
    }
    
        5
  •  2
  •   Diego    13 年前

    经过一些研究,我发现Takepara的解决方案是用Newtonsoft的JSON.NET替换默认MVC JSON反序列化程序的最佳选择。它还可以推广到程序集中的所有类型,如下所示:

    using Newtonsoft.Json;
    
    namespace MySite.Web
    {
        public class MyModelBinder : IModelBinder
        {
            // make a new Json serializer
            protected static JsonSerializer jsonSerializer = null;
    
            static MyModelBinder()
            {
                JsonSerializerSettings settings = new JsonSerializerSettings();
                // Set custom serialization settings.
                settings.DateTimeZoneHandling= DateTimeZoneHandling.Utc;
                jsonSerializer = JsonSerializer.Create(settings);
            }
    
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                object model;
    
                if (bindingContext.ModelType.Assembly == "MyDtoAssembly")
                {
                    var s = controllerContext.RequestContext.HttpContext.Request.InputStream;
                    s.Seek(0, SeekOrigin.Begin);
                    using (var sw = new StreamReader(s))
                    {
                        model = jsonSerializer.Deserialize(sw, bindingContext.ModelType);
                    }
                }
                else
                {
                    model = ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
                }
                return model;
            }
        }
    }
    

    然后,在 Global.asax.cs , Application_Start() :

            var asmDto = typeof(SomeDto).Assembly;
            foreach (var t in asmDto.GetTypes())
            {
                ModelBinders.Binders[t] = new MyModelBinder();
            }