[英]MvcOptions.InputFormatters doesn't work on asp.net vnext beta7
My application stopped working after migrating to beta 6/7, after investigating, I have found that my json deserializer is no more used ( Jil ), it's called for writing but not for reading.我的应用程序在迁移到 beta 6/7 后停止工作,经过调查,我发现我的 json 反序列化器不再使用( Jil ),它需要写入而不是读取。
It has been now 3 days that I'm searching forums and reading aspnet code but I haven't found the issue.现在已经 3 天了,我正在搜索论坛并阅读 aspnet 代码,但我还没有发现问题。
I noticed that JSON.net is used everywhere in beta 6, a little bit less in beta 7.我注意到 JSON.net 在 beta 6 中随处可见,在 beta 7 中使用的更少。
Here is my code :这是我的代码:
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();
}
Even if I do just InputFormatters.Clear() without adding an object, it keeps deserializing the requests, I have no idea how it does it.即使我只做 InputFormatters.Clear() 而不添加对象,它也会不断反序列化请求,我不知道它是如何做到的。
And my JIL InputFormatter/OutputFormatter ( the ouputformatter works, I can break in the CanWrite, but nothing happens for CanRead )还有我的 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);
}
}
只有在动作的参数列表中使用了 [FromBody] 时,才使用 InputFormatters。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.