Edg*_*gar 12 c# nullable model-binding asp.net-mvc-3
我创建了一个测试网站来调试我遇到的问题,看起来我要么传递JSON数据错误,要么MVC只能绑定可空的longs.当然,我正在使用最新的MVC 3版本.
public class GetDataModel
{
public string TestString { get; set; }
public long? TestLong { get; set; }
public int? TestInt { get; set; }
}
[HttpPost]
public ActionResult GetData(GetDataModel model)
{
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
我发布了一个具有正确JSON内容类型的JSON字符串:
{ "TestString":"test", "TestLong":12345, "TestInt":123 }
Run Code Online (Sandbox Code Playgroud)
长期没有约束,它总是空的.如果我把这个值放在引号中,它就可以工作,但我不应该这样做,不是吗?我需要为该值设置自定义模型绑定器吗?
我的同事为此想出了一个解决方法。解决方案是获取输入流并使用正则表达式将所有数字变量括在引号中,以欺骗 JavaScriptSerializer 正确反序列化长整型。这不是一个完美的解决方案,但它可以解决问题。
这是在自定义模型绑定器中完成的。我使用将 JSON 数据发布到 ASP.NET MVC作为示例。但是,如果在其他地方访问输入流,则必须小心。
public class JsonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!IsJSONRequest(controllerContext))
return base.BindModel(controllerContext, bindingContext);
// Get the JSON data that's been posted
var jsonStringData = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
// Wrap numerics
jsonStringData = Regex.Replace(jsonStringData, @"(?<=:)\s{0,4}(?<num>[\d\.]+)\s{0,4}(?=[,|\]|\}]+)", "\"${num}\"");
// Use the built-in serializer to do the work for us
return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
}
private static bool IsJSONRequest(ControllerContext controllerContext)
{
var contentType = controllerContext.HttpContext.Request.ContentType;
return contentType.Contains("application/json");
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其放入全局:
ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
Run Code Online (Sandbox Code Playgroud)
现在多头已成功绑定。我将其称为 JavaScriptSerializer 中的错误。另请注意,长整型数组或可空长整型数组在没有引号的情况下也可以很好地绑定。