ASP MVC 5 如何借助 JSON NET 从请求中读取对象

ASP MVC 5 How to read object from request with the help of JSON NET

我需要使用 JSON NET 序列化程序。

SiteModelBinder

internal class SiteModelBinder : System.Web.Mvc.IModelBinder
{
    public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
    {
        // use Json.NET to deserialize the incoming Position
        controllerContext.HttpContext.Request.InputStream.Position = 0; // see: 
        Stream stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
        var readStream = new StreamReader(stream, Encoding.UTF8);
        string json = readStream.ReadToEnd();
        return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());
    }
}

这里我在位置 0,0 得到了一个无法识别的异常字符

        return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());

ajax 通话

$.ajax({
        url: '/Site/Update',
        data: { site: getSite() },
        contentType: 'application/json',
        method: 'POST',
        success: function (data) {
            console.log('Success save');
        },
        error: function (data) {
            debugBox(data);
        }
    });

和 mvc 操作,BTW BuildBlocks 属性 是 List<AbstractBuildBlock> 类型并且 TextBlock 是派生的。

public string Update(Site site)
    {
        //the goal to see in debugger that block is not null after the next line
        TextBlock block = site.Pages[0].Rows[0].BuildBlocks[0] as TextBlock;
        //siteRepository.Add(site);
        return "Success";
    }

我错过了什么或做错了什么?

正确ajax调用

$.ajax({ 
        type: "POST",
        url: "/Site/Update",
        dataType: "json", 
        data: {JSON.stringify(filtersData) }, //without name because I'll use custom ModelBinder
        contentType: "application/json; charset=utf-8", 
        traditional: true,
        success: function (data) { 
            alert("ok"); 
        },
        error:function (xhr, ajaxOptions, thrownError) { 
            alert(xhr.status); 
            alert(thrownError); 
        }
    });