Миграция на. NET Core 3.1 - Netwonsoft отсутствует - PullRequest
1 голос
/ 14 апреля 2020

Я только что перешел на ASP. NET Core 3.1 с 2.2 и получаю эту ошибку:

System.NotSupportedException: The collection type 'System.Collections.Generic.Dictionary`2[System.Object,System.Object]' is not supported.
   at System.Text.Json.JsonClassInfo.GetElementType(Type propertyType, Type parentType, MemberInfo memberInfo, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.CreateProperty(Type declaredPropertyType, Type runtimePropertyType, Type implementedPropertyType, PropertyInfo propertyInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.AddPolicyProperty(Type propertyType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type classType)
   at System.Text.Json.WriteStackFrame.Initialize(Type type, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)

Однако я установил этот пакет Microsoft.AspNetCore.Mvc.NewtonsoftJson, а также добавил services.AddControllers().AddNewtonsoftJson() в Запуск

Итак, почему Newtonsoft по-прежнему игнорируется и используется System.Text. Json?

EDIT: Ошибка при бросании кода:

public async Task<Dictionary<object, object>> GetTemplatesDictAsync(
           int? from = 0,
            int? take = 100,
            string search = null)
        {
            var _templates = await _repository.GetAllAsync(from, take, search, );

            var _dict = _templates.ToDictionary(t => (object)t.id, t => (object)t);

            // also append a property with original list
            _dict.Add("list", _templates);

            return _dict;
        }

Примечание: я изменил Dictionary<object, object> до Dictionary<string, object> и код работает. Вопрос, однако, почему Newtonsoft. Json не используется.

EDIT2:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentications(Configuration);
            services.AddAutoMapping();
            services.AddMemoryCache();
            services.AddOData();

            // 3.1:
            services.AddControllers()
                        .AddNewtonsoftJson()
                    ;

           // used in 2.2:
           // var mvcCoreBuilder = services.AddMvcCore();
            // mvcCoreBuilder
            //     .AddFormatterMappings()
            //     .AddJsonFormatters()


Спасибо

1 Ответ

1 голос
/ 14 апреля 2020

In. NET Core 3+ проектов, у вас есть другой набор вызовов для замены MVC. Таким образом, у вас, вероятно, будет одно из следующего:

services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();

Если это не работает, пожалуйста, сообщите нам немного больше, где вы используете это.

Вы можете найти более пошаговый подход на здесь Это сработало для меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...