In ASP.NET MVC, deserialize JSON prior to or in controller's action method

后端 未结 5 784
深忆病人
深忆病人 2020-12-25 13:27

I am working on a website that will post a JSON object (using jQuery Post method) to the server side.

{ 
    \"ID\" : 1,
    \"FullName\" : {
       \"First         


        
5条回答
  •  借酒劲吻你
    2020-12-25 14:23

    After some research, I found Takepara's solution to be the best option for replacing the default MVC JSON deserializer with Newtonsoft's Json.NET. It can also be generalized to all types in an assembly as follows:

    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;
            }
        }
    }
    

    Then, in Global.asax.cs, Application_Start():

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

提交回复
热议问题