/// <summary>
    /// Adds <see cref="HtmlEncoder"/>, <see cref="JavaScriptEncoder"/> and <see cref="UrlEncoder"/>
    /// to the specified <paramref name="services" />.
    /// </summary>
    /// <param name="services">The <see cref="IServiceCollection"/>.</param>
    /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
    public static IServiceCollection AddWebEncoders(this IServiceCollection services)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        services.AddOptions();

        // Register the default encoders
        // We want to call the 'Default' property getters lazily since they perform static caching
        services.TryAddSingleton(
            CreateFactory(() => HtmlEncoder.Default, settings => HtmlEncoder.Create(settings)));
        services.TryAddSingleton(
            CreateFactory(() => JavaScriptEncoder.Default, settings => JavaScriptEncoder.Create(settings)));
        services.TryAddSingleton(
            CreateFactory(() => UrlEncoder.Default, settings => UrlEncoder.Create(settings)));

        return(services);
    }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //不加这句会(视图中的中文被html编码)
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            //内存缓存
            services.AddMemoryCache();

            services.AddDistributedMemoryCache();

            //配置session(session是根据上面cache来区分存储源地的)
            services.AddSession(opts =>
            {
                opts.IdleTimeout     = TimeSpan.FromMinutes(60); //设置Session闲置超时时间(有效时间周期)
                opts.Cookie.Name     = "Nzh.Super_cookie";
                opts.Cookie.HttpOnly = true;
            });


            //配置存储视图的默认区域文件夹
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.AreaViewLocationFormats.Clear();
                options.AreaViewLocationFormats.Add("/Views/{2}/{1}/{0}.cshtml");
                options.AreaViewLocationFormats.Add("/Views/{1}/{0}.cshtml");
                options.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddControllersWithViews()
            //配置json返回的格式
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            })
            // 将Controller加入到Services中
            .AddControllersAsServices();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            EnumScanner es  = new EnumScanner();
            var         dic = es.ToDescription(typeof(SexEnum));

            Console.WriteLine(JsonSerializer.Serialize(dic, new JsonSerializerOptions
            {
                WriteIndented = true
            }));

            var dics = es.Scan <SexEnum>();

            Console.WriteLine(JsonSerializer.Serialize(dics, new JsonSerializerOptions
            {
                WriteIndented = true,
                Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All)
            }));

            Console.WriteLine(SexEnum.Female.ToDescription());
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigurationHelper.Configure(Configuration);
            services.AddControllersWithViews();
            //添加认证Cookie信息

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath        = new PathString("/Home/Login");
                options.AccessDeniedPath = new PathString("/Home/CusError");
            });
            services.AddMvc().AddNewtonsoftJson().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.PropertyNamingPolicy        = JsonNamingPolicy.CamelCase;
            });

            RegisterServices(services);
        }
Ejemplo n.º 5
0
        public async Task <string> GetPriceListOfToolTypeAsync(string ToolTypeId)
        {
            var toolType = await ReadToolTypeAsync(ToolTypeId);

            Dictionary <string, string> toolTypePriceList = new Dictionary <string, string>();

            for (int i = 0; i < toolType.Serves.Length; i++)
            {
                toolTypePriceList.Add(toolType.Serves[i], toolType.Costs[i]);
            }

            var options = new JsonSerializerOptions()
            {
                AllowTrailingCommas  = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All), //поможет с кодировкой
                WriteIndented = true
            };

            return(JsonSerializer.Serialize(toolTypePriceList, options));
        }
Ejemplo n.º 6
0
        public IActionResult GetFood(string name)
        {
            FoodContext fc = context;
            // 出力テスト
            // foreach (FoodModel FoodModel in fc.FoodModel) {
            //     Console.WriteLine ("id:{0}, name:{1}", FoodModel.FoodId, FoodModel.Name);
            // }
            // foreach (LocationModel LocationModel in fc.LocationModel) {
            //     Console.WriteLine ("id:{0}, name:{1}", LocationModel.LocationId, LocationModel.Name);
            // }
            // foreach (UserModel UserModel in fc.UserModel) {
            //     Console.WriteLine ("id:{0}, login_id:{1}, name:{2}, password:{3}", UserModel.UserId, UserModel.LoginId, UserModel.Name, UserModel.Password);
            // }
            IEnumerable <FoodModel> fm;

            fm = fc.FoodModel.Where(x => x.Name.Contains(name)).ToList();
            return(Json(fm, new JsonSerializerOptions {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                WriteIndented = true,
            }));
        }
Ejemplo n.º 7
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AppDbContext>();

            services.AddCap(x =>
            {
                x.UseEntityFramework <AppDbContext>();
                x.UseRabbitMQ("");
                x.UseDashboard();
                x.FailedRetryCount        = 5;
                x.FailedThresholdCallback = failed =>
                {
                    var logger = failed.ServiceProvider.GetService <ILogger <Startup> >();
                    logger.LogError($@"A message of type {failed.MessageType} failed after executing {x.FailedRetryCount} several times, 
                        requiring manual troubleshooting. Message name: {failed.Message.GetName()}");
                };
                x.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });

            services.AddControllers();
        }
Ejemplo n.º 8
0
        public static string ToJson(Object obj, JSONOPTIONS options)
        {
            if (obj == null)
            {
                return(String.Empty);
            }

            if (options == null)
            {
                options = new JSONOPTIONS
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    IgnoreNullValues     = true,
                    WriteIndented        = true,
                    // 防止序列化中文字符
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                };
            }

            return(JsonSerializer.Serialize(obj, obj.GetType(), options));
        }
Ejemplo n.º 9
0
        public IActionResult Error()
        {
            var feature   = HttpContext.Features.Get <IExceptionHandlerFeature>();
            var exception = feature.Error; // Your exception

            //session error 체크

            if (exception is ApiSessionTimeoutException)
            {
                JsonReturnModel returnModel = new JsonReturnModel();
                returnModel.IsSession = false;
                returnModel.IsSuccess = false;
                returnModel.Msg       = exception.Message;

                var options = new JsonSerializerOptions
                {
                    Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All, UnicodeRanges.All),
                    WriteIndented = true
                };
                return(Ok(returnModel));
                //string jsonstring = JsonSerializer.Serialize<JsonReturnModel>(returnModel, options);
                //HttpContext.Response.ContentType = "application/json;charset=UTF-8";
                ////context.HttpContext.Response.ContentType = "application/json";
                //HttpContext.Response.WriteAsync(jsonstring);
            }
            else
            {
                return(View(new ErrorViewModel {
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Message = exception.Message
                }));
            }


            //if (exception is SessionTimeoutException)
            //{
            //    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Message = exception.Message });
            //}

            //return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Message= exception.Message);
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="secretKey"></param>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns>签名后的URL</returns>
        public static string TrySignaturedPost(string secretKey, string url, string json)
        {
            if (string.IsNullOrWhiteSpace(secretKey))
            {
                return(url);
            }

            var uri = new Uri(url);

            var path = uri.AbsolutePath;
            // 获取json对象中的所有一级属性
            var rootElements = JsonSerializer.Deserialize <Dictionary <string, object> >(json);
            // 将所有一级属性值转换成最紧凑化字符串
            var shrinkRootElements          = new Dictionary <string, string>();
            var shrinkJsonSerializerOptions = new JsonSerializerOptions()
            {
                AllowTrailingCommas = false,
                WriteIndented       = false,
                ReadCommentHandling = JsonCommentHandling.Skip,
                Encoder             = JavaScriptEncoder.Create(UnicodeRanges.All),
            };

            foreach (var key in rootElements.Keys)
            {
                var value       = rootElements[key];
                var shrinkValue = JsonSerializer.Serialize(value, typeof(object), shrinkJsonSerializerOptions);
                shrinkValue = shrinkValue.Trim('"');
                shrinkRootElements.Add(key, shrinkValue);
            }
            // 将所有一级属性转换成key=value形式字符串,如:data=[{"ud_id":"156985","title":"海淀区苏州街营业部","location":{"lat":39.983988,"lng":116.307709},"x":{"price":15.5}}]&key=5Q5BZ-5EVWJ-SN5F3-K6QBZ-*****&table_id=5d405395d230bf1d9416be10
            // 排序后用&连接
            var orderedJsonQuery = string.Join("&", shrinkRootElements.Select(x => x.Key + "=" + x.Value).OrderBy(x => x).ToArray());
            var newPathAndQuery  = $"{path}?{orderedJsonQuery}{secretKey}";
            var md5       = System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(newPathAndQuery));
            var signature = BitConverter.ToString(md5).Replace("-", "").ToLower();

            var newUrl = url + (url.IndexOf('?') > 0 ? "&" : "?") + "sig=" + signature;

            return(newUrl);
        }
Ejemplo n.º 11
0
        public static void Set(this ISession Session, string key, object data, bool jsonIndentFormat = false)
        {
            if (data == null)
            {
                return;
            }
            var json = "";

            if (jsonIndentFormat)
            {
                json = JsonSerializer.Serialize(data, new JsonSerializerOptions()
                {
                    WriteIndented = true,
                    Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All)
                });
            }
            else
            {
                json = JsonSerializer.Serialize(data, JsonSerializerOptions);
            }
            Session.SetString(key, json);
        }
Ejemplo n.º 12
0
        static string  ReduceTheNumberOfPoints(string jsonElement, int N)
        {
            var options = new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
                          //,WriteIndented = true
            };
            JsonDocument doc         = JsonDocument.Parse(jsonElement);
            string       geojsontype = doc.RootElement.GetProperty("geojson").GetProperty("type").ToString();

            switch (geojsontype)
            {
            case "Point":
                break;

            case "LineString":
                PolyData <GeoJsonLineString> polydataLineString = JsonSerializer.Deserialize <PolyData <GeoJsonLineString> >(jsonElement);
                polydataLineString.geojson.ReduceTheNumberOfPoints(N);
                jsonElement = JsonSerializer.Serialize(polydataLineString, options);
                break;

            case "Polygon":
                PolyData <GeoJsonPolygon> geoJsonPolygon = JsonSerializer.Deserialize <PolyData <GeoJsonPolygon> >(jsonElement);
                geoJsonPolygon.geojson.ReduceTheNumberOfPoints(N);
                jsonElement = JsonSerializer.Serialize(geoJsonPolygon, options);
                break;

            case "MultiPolygon":
                PolyData <GeoJsonMultiPolygon> geoJsonMultiPolygon = JsonSerializer.Deserialize <PolyData <GeoJsonMultiPolygon> >(jsonElement);
                geoJsonMultiPolygon.geojson.ReduceTheNumberOfPoints(N);
                jsonElement = JsonSerializer.Serialize(geoJsonMultiPolygon, options);
                break;

            default:
                Console.WriteLine("Unknown geojson type:" + geojsontype);
                break;
            }
            return(jsonElement);
        }
Ejemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.AddScoped <ViewRenderService>();

            services.AddTransient <IPasswordValidator <UserModel>,
                                   CustomPasswordValidator>(serv => new CustomPasswordValidator());

            services.AddTransient <IUserValidator <UserModel>,
                                   CustomUserValidator>(serv => new CustomUserValidator());

            services.Configure <RouteOptions>(o => o.LowercaseUrls = true);
            services.AddDbContext <DataContext>();
            services.AddControllersWithViews(op => op.EnableEndpointRouting = false)
            .AddRazorRuntimeCompilation()
            .AddNewtonsoftJson()
            .AddJsonOptions(op => op.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic));
            services.AddIdentity <UserModel, IdentityRole>(o => { o.User.RequireUniqueEmail = true; o.SignIn.RequireConfirmedEmail = true; })
            .AddEntityFrameworkStores <DataContext>()
            .AddDefaultTokenProviders();
        }
Ejemplo n.º 14
0
        public T Deserialize(string data)
        {
            var movies = new T();

            _logger.LogInformation($"Deserializing message.");
            try
            {
                var options = new JsonSerializerOptions
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),

                    WriteIndented = true
                };
                options.Converters.Add(new GuidConverter());
                movies = JsonSerializer.Deserialize <T>(data, options);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error while deserializing data. Error: {ex.Message}, InnerException {ex.InnerException?.Message}, Stack {ex.StackTrace}");
            }
            return(movies);
        }
Ejemplo n.º 15
0
        public static async Task WriteJson(string filename, BasicExampleElement element)
        {
            // シリアライズ時のオプション
            var serializerOptions = new JsonSerializerOptions()
            {
                // 日本語文字のユニコードエスケープを防止
                // (例えば "あ" が "\u3042" のようにエスケープされないようにする。)
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                // 人が参照しやすいようインデントを付与(不要であれば、このオプションは除外)
                WriteIndented = true,
                // キャメルケースでJsonフィールドを使用(既定はパスカルケース)
                // (例: MyNameプロパティは、myNameというJsonフィールドとして出力)
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            // DateTime既定の日付書式を変更
            serializerOptions.Converters.Add(new DateTimeLocalConverter());

            // JSONの出力
            using var stream = new FileStream(filename, FileMode.OpenOrCreate | FileMode.CreateNew);
            await JsonSerializer.SerializeAsync(stream, element, serializerOptions);
        }
Ejemplo n.º 16
0
        public static Setting GetSettingFromFile(string path)
        {
            var options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                PropertyNameCaseInsensitive = true,
                WriteIndented = true
            };
            var setting = new Setting();

            if (!File.Exists(path))
            {
                string json = JsonSerializer.Serialize(setting, options);
                File.WriteAllText(path, json);
                return(setting);
            }
            string set = File.ReadAllText(path);

            setting = JsonSerializer.Deserialize <Setting>(set, options);

            return(setting);
        }
Ejemplo n.º 17
0
        public void OnConfigureServices(IServiceCollection services)
        {
            var provider  = services.BuildServiceProvider();
            var mvcConfig = provider.GetService <IOptions <AppConfigOption> >()?.Value.MvcConfig;

            if (mvcConfig?.IsFluentValidate ?? false)
            {
                var assemblyList = mvcConfig.AssemblyNameList.Select(_ => Assembly.Load(new AssemblyName(_)));

                services.AddMvcCore().AddFluentValidation(fv =>
                {
                    foreach (var assembly in assemblyList)
                    {
                        fv.RegisterValidatorsFromAssembly(assembly);
                    }
                })
                .ConfigureApiBehaviorOptions(options =>
                {
                    options.InvalidModelStateResponseFactory = (context) => new BadRequestObjectResult(context.ModelState);
                })
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                });
            }
            else
            {
                services.AddMvcCore()
                .AddDataAnnotations()
                .ConfigureApiBehaviorOptions(options =>
                {
                    options.InvalidModelStateResponseFactory = (context) => new BadRequestObjectResult(context.ModelState);
                })
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                });
            }
        }
Ejemplo n.º 18
0
        public static async Task SerializationJsonAsync(string jsonPath, object value)
        {
            string json = string.Empty;

            using (var stream = new MemoryStream())
            {
                JsonSerializerOptions options = new JsonSerializerOptions();
                options.WriteIndented = true;
                options.Encoder       = JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All);
                if (!File.Exists(jsonPath))
                {
                    using var file = File.Create(jsonPath);
                }
                await JsonSerializer.SerializeAsync(stream, value, value.GetType(), options);

                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    await File.WriteAllTextAsync(jsonPath, await reader.ReadToEndAsync());
                }
            }
        }
Ejemplo n.º 19
0
        private void ConfigureJobs(int maxThreads)
        {
            JsonWriterOptions options = new JsonWriterOptions
            {
                Indented = false,
                Encoder  = JavaScriptEncoder.Create(UnicodeRanges.All)
            };

            for (int i = 0; i < maxThreads; i++)
            {
                JobInfo job = new JobInfo()
                {
                    Channel = CreateChannel()
                };
                job.Properties = CreateMessageProperties(job.Channel);

                job.Stream = _streamManager.GetStream();
                job.Writer = new Utf8JsonWriter(job.Stream, options);

                LIST_OF_JOBS.Add(job);
            }
        }
Ejemplo n.º 20
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <BankingDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("BankingDbConnectionString"));
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Banking Microservice", Version = "v1"
                });
            });

            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.WriteIndented = true;
                options.JsonSerializerOptions.Encoder       = JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All);
            });
            services.RegisterServices();
            services.AddMediatR(typeof(Startup));
        }
Ejemplo n.º 21
0
        public void WriteToStream(Stream stream)
        {
            var writerOptions = new JsonWriterOptions
            {
                Indented       = true,
                Encoder        = JavaScriptEncoder.Create(new TextEncoderSettings(UnicodeRanges.All)),
                SkipValidation = false
            };

            using var writer = new Utf8JsonWriter(stream, options: writerOptions);

            writer.WriteStartObject();

            foreach (var element in dictionary.OrderBy(x => x.Key))
            {
                writer.WritePropertyName(element.Key);
                using JsonDocument document = JsonDocument.Parse(element.Value);
                document.WriteTo(writer);
            }

            writer.WriteEndObject();
        }
Ejemplo n.º 22
0
        public async Task writingToFileAsync(List <string> str)
        {
            /*
             * List<string> str = new List<string>();
             * for (int i = 0; i < _table.Count; i++)
             * {
             *      str.Add(Convert.ToString(_table[i].Text));
             * }
             */

            JsonSerializerOptions options = new JsonSerializerOptions
            {
                Encoder       = JavaScriptEncoder.Create(UnicodeRanges.All),
                WriteIndented = true
            };


            // сохранение данных
            using (FileStream fs = new FileStream("Equipment.json", FileMode.OpenOrCreate))
            {
                //записывает как UTF-8, но отображаются как ASCII символы
                await JsonSerializer.SerializeAsync <List <string> >(fs, str, options);

                Console.WriteLine("Data has been saved to file Equipment.json");
            }

            /*
             * // чтение данных
             * using (FileStream fs = new FileStream("Table.json", FileMode.OpenOrCreate))
             * {
             *      List<string> restoredTable = await JsonSerializer.DeserializeAsync<List<string>>(fs);
             *      for (int i = 0; i < restoredTable.Count; i++)
             *      {
             *              Console.WriteLine(restoredTable[i]);
             *      }
             * }
             */
        }
Ejemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <CzadsbDbContext>(dbContextOptions =>
                                                    dbContextOptions.UseNpgsql("Host=127.0.0.1;Database=czadsb;Username=root;Password=password"));
            services.AddIdentity <User, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail         = true;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores <CzadsbDbContext>().AddDefaultTokenProviders();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost";
                options.InstanceName  = "Redis";
            });

            services.AddControllersWithViews()
            .AddRazorRuntimeCompilation()
            .AddJsonOptions(json =>
            {
                json.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
            services.AddRazorPages();

            services.AddTransient <IEmailSender, EmailSender>();
            services.AddScoped <JoshApiService>();
            services.AddSingleton <CzadsbRedis>();
            services.AddSignalR();
            services.AddSignalRCore();

            /* Add IManagementUtils into DI Container */
            services.Scan(scan => scan.FromAssemblyOf <IManagementUtil>()
                          .AddClasses(classes => classes.AssignableTo <IManagementUtil>())
                          .AsImplementedInterfaces().WithTransientLifetime());
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            // Title каждой ноды должен быть уникальным (в файлах .dot и .dot.svg это не так).
            // В .dot.svg неправильно отображается "Соколина Гора" и "Марьина роща".
            // Правильный и актуальный .json находится в AISystemsModule/Resources.
            string sourcePath = "./Resources/moscow.json";
            string outputPath = sourcePath.Replace(".json", ".attributes.json");

            // Считываем дерево из файла.
            string text = File.ReadAllText(sourcePath);
            Node   root = JsonSerializer.Deserialize <Node>(text);

            // Заполняем листья случайными значениями.
            root.AddAttributesToLeafs();

            // Записываем дерево в файл.
            var options = new JsonSerializerOptions {
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
            };
            var result = JsonSerializer.SerializeToUtf8Bytes(root, options);

            File.WriteAllBytes(outputPath, result);
        }
Ejemplo n.º 25
0
        private void Serialize1()
        {
            JsonWriterOptions options = new JsonWriterOptions()
            {
                Indented = false,
                Encoder  = JavaScriptEncoder.Create(UnicodeRanges.All)
            };

            using (MemoryStream stream = new MemoryStream())
            {
                using (Utf8JsonWriter writer = new Utf8JsonWriter(stream, options))
                {
                    writer.WriteStartObject();
                    foreach (string item in TestValues)
                    {
                        writer.WriteString(item, item);
                    }
                    writer.WriteEndObject();
                    writer.Flush();
                }
                //byte[] result = stream.ToArray();
            }
        }
Ejemplo n.º 26
0
        public void Relaxed_EquivalentToAll_WithExceptions()
        {
            // Arrange
            JavaScriptEncoder controlEncoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            JavaScriptEncoder testEncoder    = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

            // Act & assert
            for (int i = 0; i <= char.MaxValue; i++)
            {
                if (i == '"' || i == '&' || i == '<' || i == '>' || i == '+' || i == '\'' || i == '`')
                {
                    string input = new string((char)i, 1);
                    Assert.NotEqual(controlEncoder.Encode(input), testEncoder.Encode(input));
                    continue;
                }

                if (!IsSurrogateCodePoint(i))
                {
                    string input = new string((char)i, 1);
                    Assert.Equal(controlEncoder.Encode(input), testEncoder.Encode(input));
                }
            }
        }
Ejemplo n.º 27
0
        public JsonSerializerOptions GetJsonSerializerOptions(
            bool writeIndented            = false,
            JsonNamingPolicy?namingPolicy = null)
        {
            var encoderSettings = new TextEncoderSettings();

            // Additional options are needed to correct serialization of polish diacritic letters.
            encoderSettings.AllowRange(UnicodeRanges.BasicLatin);
            encoderSettings.AllowRange(UnicodeRanges.Latin1Supplement);
            encoderSettings.AllowRange(UnicodeRanges.LatinExtendedA);
            var options = new JsonSerializerOptions()
            {
                WriteIndented = writeIndented,
                Encoder       = JavaScriptEncoder.Create(encoderSettings)
            };

            if (namingPolicy != null)
            {
                options.PropertyNamingPolicy = namingPolicy;
            }

            return(options);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> ObterPorCpf(Guid userId)
        {
            var    cacheName = $"{_cache}-{userId}";
            string jsonCache = await _cache.GetCache(cacheName);

            if (string.IsNullOrEmpty(jsonCache))
            {
                var cpf = await _usuarioService.ObterCpfUsuario(userId);

                var data = await _sturService.ObterIptuPorCpf(cpf);

                var jsOption = new JsonSerializerOptions
                {
                    Encoder       = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic),
                    WriteIndented = true
                };
                jsonCache = JsonSerializer.Serialize(data, jsOption);

                _cache.CreateCache(cacheName, jsonCache, 5);
            }

            return(CustomResponse(jsonCache));
        }
        private static void AddWebRyeCore(IServiceCollection serviceCollection)
        {
            using (var scopeProvider = serviceCollection.BuildServiceProvider().CreateScope())
            {
                var webOptions = scopeProvider.ServiceProvider.GetRequiredService <IOptions <RyeWebOptions> >().Value;
                serviceCollection.AddControllers(options =>
                {
                    if (webOptions.GlobalActionFilter.Enabled)
                    {
                        options.Filters.Add <GlobalActionFilter>();
                    }

                    if (webOptions.ModeValidation.Enabled)
                    {
                        //关闭默认检查
                        serviceCollection.Configure <ApiBehaviorOptions>(options =>
                        {
                            options.SuppressModelStateInvalidFilter = true;
                        });

                        options.Filters.Add <ModelValidationAttribute>();
                    }
                })
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                    options.JsonSerializerOptions.PropertyNamingPolicy        = JsonNamingPolicy.CamelCase;
                    options.JsonSerializerOptions.DictionaryKeyPolicy         = JsonNamingPolicy.CamelCase;
                    //options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
                    options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
                    options.JsonSerializerOptions.WriteIndented  = true;
                    options.JsonSerializerOptions.Encoder        = JavaScriptEncoder.Create(UnicodeRanges.All);
                    options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
                    options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetJsonConverter());
                });
            }
        }
Ejemplo n.º 30
0
        public void ConfigureServices(IServiceCollection services)
        {
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            //ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            //AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            services.AddSession();
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });;

            //将第三方登录组件注入进去
            services.AddSingleton(new Baidu.BaiduOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:baidu")));
            services.AddSingleton(new Wechat.WechatOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:wechat")));
            services.AddSingleton(new Gitlab.GitlabOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:gitlab")));
            services.AddSingleton(new Gitee.GiteeOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:gitee")));
            services.AddSingleton(new Github.GithubOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:github")));
            services.AddSingleton(new Huawei.HuaweiOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:huawei")));
            services.AddSingleton(new Coding.CodingOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:coding"), Configuration["oauth:coding:team"]));
            services.AddSingleton(new SinaWeibo.SinaWeiboOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:sinaweibo")));
            services.AddSingleton(new Alipay.AlipayOAuth(
                                      OAuthConfig.LoadFrom(Configuration, "oauth:alipay"),
                                      Configuration["oauth:alipay:private_key"],
                                      Configuration["oauth:alipay:public_key"],
                                      Configuration["oauth:alipay:encrypt_key"]
                                      ));
            services.AddSingleton(new QQ.QQOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:qq")));
            services.AddSingleton(new OSChina.OSChinaOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:oschina")));
            services.AddSingleton(new DouYin.DouYinOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:douyin")));
            services.AddSingleton(new WechatOpen.WechatOpenOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:wechatopen")));
            services.AddSingleton(new MeiTuan.MeiTuanOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:meituan")));
            services.AddSingleton(new XunLei.XunLeiOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:xunlei")));
        }