我的应用程序在迁移到beta 6/7之后停止工作,在调查之后,我发现我的json反序列化器不再使用(Jil),它被要求写入而不是用于阅读.
现在已经3天了,我正在搜索论坛并阅读aspnet代码,但我还没有找到问题.
我注意到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();
}
Run Code Online (Sandbox Code Playgroud)
即使我只是在没有添加对象的情况下执行InputFormatters.Clear(),它也会对请求进行反序列化,我不知道它是如何做到的.
我的JIL InputFormatter/OutputFormatter(ouputformatter工作,我可以在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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
805 次 |
最近记录: |