【发布时间】:2015-08-18 22:43:24
【问题描述】:
我的应用程序在迁移到 beta 6/7 后停止工作,经过调查,我发现我的 json 反序列化器不再使用( Jil ),它被称为写入而不是读取。
我在搜索论坛和阅读aspnet代码已经3天了,但我还没有发现问题。
我注意到 JSON.net 在 beta 6 中无处不在,而在 beta 7 中则少一些。
这是我的代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore(options =>
{
var jilFormatter = new JilMediaTypeFormatter();
options.OutputFormatters.Clear();
options.OutputFormatters.Add(jilFormatter);
options.InputFormatters.Clear();
options.InputFormatters.Add(jilFormatter);
options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));
options.ModelBinders.Add(new DocumentModelBinder());
options.ModelBinders.Add(new DataTablesBinder());
});
services.AddDataProtection();
services.AddWebEncoders();
}
即使我只执行 InputFormatters.Clear() 而不添加对象,它也会不断反序列化请求,我不知道它是如何做到的。
还有我的 JIL InputFormatter/OutputFormatter(输出格式化程序有效,我可以中断 CanWrite,但 CanRead 没有任何反应)
internal class JilMediaTypeFormatter : IOutputFormatter, IInputFormatter
{
private static readonly string [] _readableTypes = new[] { "application/json", "text/json", "text/javascript" };
private static readonly Task<bool> _done = Task.FromResult(true);
private readonly Options _options = Options.RFC1123ExcludeNullsIncludeInherited;
public bool CanWriteResult(OutputFormatterContext context, Microsoft.Net.Http.Headers.MediaTypeHeaderValue contentType)
{
return contentType ==null || _readableTypes.Contains(contentType.MediaType.ToLowerInvariant());
}
public Task WriteAsync(OutputFormatterContext context)
{
context.HttpContext.Response.ContentType = "application/json";
using (var writer = new StreamWriter(context.HttpContext.Response.Body))
{
JSON.Serialize(context.Object, writer, _options);
writer.Flush();
return _done;
}
}
public bool CanRead(InputFormatterContext context)
{
return _readableTypes.Contains(context.HttpContext.Request.ContentType);
}
public Task<object> ReadAsync(InputFormatterContext context)
{
var reader = new StreamReader(context.HttpContext.Request.Body);
var result = JSON.Deserialize(reader, context.ModelType, _options);
return Task.FromResult(result);
}
}
【问题讨论】:
标签: c# asp.net-core