ASPNET Core 2.1.2忽略输出格式化程序NotAcceptable = true

时间:2018-07-13 17:20:01

标签: asp.net-core

Json工作正常,但是我添加的所有其他格式化程序都将被忽略。

我有以下内容:

            var builder = services.AddMvcCore(options =>
        {
            options.RespectBrowserAcceptHeader = true;
            options.ReturnHttpNotAcceptable = true;
            var jsonSerializerSettings = new JsonSerializerSettings
            {

如果(调试)

                Formatting = Formatting.Indented,

endif

                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                ContractResolver = new DefaultContractResolver(),
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
            };
            jsonSerializerSettings.Converters.Add(new IsoDateTimeConverter
            {
                DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal
            });


            var sp = services.BuildServiceProvider();

            options.InputFormatters.Add(new JsonInputFormatter(sp.GetService<ILoggerFactory>().CreateLogger("JsonInputFormatter"), jsonSerializerSettings, ArrayPool<char>.Create(), services.BuildServiceProvider().GetService<ObjectPoolProvider>(), options, new MvcJsonOptions
            {
                AllowInputFormatterExceptionMessages = true
            }));


            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(new MvcOptions
            {
            }));

            options.OutputFormatters.Add(new JsonOutputFormatter(jsonSerializerSettings, ArrayPool<char>.Create()));
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());

        })
            .AddApiExplorer()
            .AddVersionedApiExplorer(o =>
            {
                o.GroupNameFormat = "'v'VVV";
                o.SubstituteApiVersionInUrl = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.AssumeDefaultVersionWhenUnspecified = true;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddAuthorization()
            .AddDataAnnotations()
            .AddFormatterMappings()
            .AddCors()
            .AddRazorPages();

如果我然后使用Postman并将Accept标头设置为application / json,则效果很好。

如果我将其设置为application / xml,它将返回406,这是不可接受的。如果我禁用ReturnHttpNotAcceptable,那么它只会返回json。

我正在设置json等,因为我通常有更多的格式化程序(需要jsonserializer的bson),但是我禁用了所有这些格式化程序,但仍然没有任何乐趣。

让这些格式化程序正常工作到底在做什么呢?

0 个答案:

没有答案