这与此question相关,但在本例中,它不是我要返回的内容,而是模型绑定。我正在使用Postmark来处理传入的电子邮件,这些邮件会发布到带有JSON payload的页面。
我有一个如下所示的模型和一个接受此JSON有效负载(通过application/json发布)并对其进行处理的操作。
public class EmailModel
{
public IDictionary<string, string> Headers { get; set; }
public string From { get; set; }
public string Cc { get; set; }
public string HtmlBody { get; set; }
public string TextBody { get; set; }
public string ReplyTo { get; set; }
public string Tag { get; set; }
public string To { get; set; }
public string MessageID { get; set; }
public string MailboxHash { get; set; }
public string Subject { get; set; }
public List<Attachment> Attachments { get; set; }
}
public class Attachment
{
public string Content { get; set; }
public int ContentLength { get; set; }
public string ContentType { get; set; }
public string Name { get; set; }
}这对于小附件很有效,但是对于任何超过默认maxJsonLength属性的附件,都会导致反序列化错误。(“使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过了在maxJsonLength属性上设置的值。”)因为我想接受图像附件,这意味着大多数图像都会失败。
我尝试过更新web.config,但根据其他线程,这对MVC控制器没有帮助。我认为我可能可以做定制IModelBinder中提到的事情,但我正在为如何拦截反序列化而苦苦挣扎。(换句话说,它仍然失败,因为反序列化已经发生了)。
有什么建议吗?我相信这只是我错过了一些愚蠢的东西...
发布于 2012-03-06 15:01:01
您可以编写一个使用Json.NET的custom JsonValueProviderFactory
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
var bodyText = reader.ReadToEnd();
return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()) , CultureInfo.CurrentCulture);
}
}在你的Application_Start中
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());https://stackoverflow.com/questions/9577375
复制相似问题