示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin(); // For anyone access.
            //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("MyPolicy", corsBuilder.Build());
            });
            var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            services.AddMvc(options =>
            {
                options.OutputFormatters.RemoveType <TextOutputFormatter>();
                options.OutputFormatters.RemoveType <HttpNoContentOutputFormatter>();
                options.OutputFormatters.Add(new JsonOutputFormatter(formatterSettings, System.Buffers.ArrayPool <Char> .Create()));
            });

            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
            //});
        }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityBuilder identityBuilder = services.AddIdentity <User, IdentityRole>(config =>
            {
                //Require confirmed email to login
                config.SignIn.RequireConfirmedEmail = true;
            }).AddDefaultTokenProviders();

            services.AddInfrastructureServices(Configuration, identityBuilder);
            services.AddWebManagers();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;

                // User settings
                options.User.RequireUniqueEmail = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.LoginPath         = "/Account/Login";         // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath        = "/Account/Logout";        // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.SlidingExpiration = true;
            });

            //Session settings
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.AreaViewLocationFormats.Clear();

                options.AddHomeViews();
                options.AddCmsViews();
            });

            services.AddMvc()
            .AddJsonOptions(options => {
                options.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                options.SerializerSettings.ContractResolver           = new CamelCasePropertyNamesContractResolver();
            })
            .AddMvcOptions(c => {
                var jsonOutputFormatter = new JsonOutputFormatter(JsonSerializerSettingsProvider.CreateSerializerSettings(), ArrayPool <Char> .Shared);
                c.OutputFormatters.Add(new JsonHalOutputFormatter(new string[] { "application/hal+json", "application/vnd.example.hal+json", "application/vnd.example.hal.v1+json" }));
            });
        }
示例#3
0
        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <remarks>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </remarks>
        /// <param name="services">The service collection.</param>
        /// <returns>The service provider.</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services
            .AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidationExceptionFilter));
                options.Filters.Add(typeof(ValidateModelAttribute));
                options.OutputFormatters.Clear();
                options.OutputFormatters.Add(new SelectFieldJsonOutputFormatter(JsonSerializerSettingsProvider.CreateSerializerSettings(), ArrayPool <char> .Shared));
            });

            // You can also use in memory database instead if you don't have SQL Server.
            services.AddDbContext <ExampleContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Example")));
            services.AddSwaggerGen(SetupSwagger);

            // Add Autofac
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterModule <DefaultModule>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();

            InitContext(container.Resolve <ExampleContext>());

            return(new AutofacServiceProvider(container));
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services
            .AddMvc(options =>
            {
                options.Filters.Add(typeof(ExceptionFilter));
                options.Filters.Add(typeof(ValidateModelAttribute));
                options.OutputFormatters.Clear();
                options.OutputFormatters.Add(new SelectFieldJsonOutputFormatter(JsonSerializerSettingsProvider.CreateSerializerSettings(), ArrayPool <char> .Shared));
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
            });

            services.AddDbContext <ExampleContext>(options => options.UseInMemoryDatabase("Test"));

            // Add Autofac
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterModule <DefaultModule>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();

            return(new AutofacServiceProvider(container));
        }
示例#5
0
        public TestMvcOptions()
        {
            Value = new MvcOptions();
            var optionsSetup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            optionsSetup.Configure(Value);

            var collection = new ServiceCollection().AddOptions();

            collection.AddSingleton <ICompositeMetadataDetailsProvider, DefaultCompositeMetadataDetailsProvider>();
            collection.AddSingleton <IModelMetadataProvider, DefaultModelMetadataProvider>();
            collection.AddSingleton <IValidationAttributeAdapterProvider, ValidationAttributeAdapterProvider>();
            MvcDataAnnotationsMvcOptionsSetup.ConfigureMvc(
                Value,
                collection.BuildServiceProvider());

            var loggerFactory      = new LoggerFactory();
            var serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            MvcJsonMvcOptionsSetup.ConfigureMvc(
                Value,
                serializerSettings,
                loggerFactory,
                ArrayPool <char> .Shared,
                new DefaultObjectPoolProvider());
        }
示例#6
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            return(services.BuildServiceProvider <AppSettings>(options =>
            {
                options.SwaggerOptions = _swaggerOptions;

                options.ConfigureMvcOptions = mvcOptions =>
                {
                    var formatter =
                        mvcOptions.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter));
                    var jsonFormatter = formatter as JsonOutputFormatter;
                    var formatterSettings = jsonFormatter == null
                        ? JsonSerializerSettingsProvider.CreateSerializerSettings()
                        : jsonFormatter.PublicSerializerSettings;
                    if (formatter != null)
                    {
                        mvcOptions.OutputFormatters.RemoveType <JsonOutputFormatter>();
                    }
                    formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ";
                    JsonOutputFormatter jsonOutputFormatter =
                        new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create());
                    mvcOptions.OutputFormatters.Insert(0, jsonOutputFormatter);
                };

                options.Logs = logs =>
                {
                    logs.AzureTableName = "TierLog";
                    logs.AzureTableConnectionStringResolver = settings => settings.TierService.Db.LogsConnString;
                };
            }));
        }
示例#7
0
    public async Task JsonOutputFormatter_ReturnsIndentedJson()
    {
        // Arrange
        var user = new FormatterWebSite.User()
        {
            Id          = 1,
            Alias       = "john",
            description = "This is long so we can test large objects " + new string('a', 1024 * 65),
            Designation = "Administrator",
            Name        = "John Williams"
        };

        var serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

        serializerSettings.Formatting = Formatting.Indented;
        var expectedBody = JsonConvert.SerializeObject(user, serializerSettings);

        // Act
        var response = await Client.GetAsync("http://localhost/JsonFormatter/ReturnsIndentedJson");

        // Assert
        await response.AssertStatusCodeAsync(HttpStatusCode.OK);

        var actualBody = await response.Content.ReadAsStringAsync();

        Assert.Equal(expectedBody, actualBody);
    }
示例#8
0
        private Task HandleExceptionAsync(HttpContext context, ILogger <TratarExcecoesMiddleware> logger, Exception exception)
        {
            logger.LogError(exception, "Ocorreu um erro na chamada: ", context.Request.Method, context.Request.Path);

            context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";

            var exceptionInfo = new Dictionary <string, object>
            {
                ["Mensagem"] = "Ocorreu um erro na sua requisição. Tente novamente mais tarde."
            };

            if (env.IsDevelopment())
            {
                exceptionInfo["Mensagem"] = exception.Message;
                if (exception.InnerException != null)
                {
                    exceptionInfo["DetalhesErro"] = new Dictionary <string, object>
                    {
                        ["Erro"]     = exception.InnerException.GetType().Name,
                        ["Detalhes"] = exception.InnerException.Message
                    };
                }
            }

            var result = JsonConvert.SerializeObject(exceptionInfo, JsonSerializerSettingsProvider.CreateSerializerSettings());

            return(context.Response.WriteAsync(result));
        }
示例#9
0
        public NewtonsoftJsonModelBinder(
            IHttpRequestStreamReaderFactory readerFactory,
            ILoggerFactory loggerFactory,
            IOptions <MvcOptions> optionsProvider,
            IOptions <MvcNewtonsoftJsonOptions> newtonsoftOptionsProvider,
            ArrayPool <char> charPool,
            ObjectPoolProvider objectPoolProvider)
        {
            var options    = optionsProvider.Value;
            var formatters = options.InputFormatters.ToList();

            var jsonFormatter           = formatters.OfType <SystemTextJsonInputFormatter>().FirstOrDefault();
            var newtonsoftJsonFormatter = formatters.OfType <NewtonsoftJsonInputFormatter>().FirstOrDefault();

            if (jsonFormatter != null && newtonsoftJsonFormatter == null)
            {
                var jsonFormatterIndex = formatters.IndexOf(jsonFormatter);
                var logger             = loggerFactory.CreateLogger <NewtonsoftJsonInputFormatter>();
                var settings           = JsonSerializerSettingsProvider.CreateSerializerSettings();

                formatters[jsonFormatterIndex] = new NewtonsoftJsonInputFormatter(
                    logger, settings, charPool, objectPoolProvider, options, newtonsoftOptionsProvider.Value);
            }

            _bodyBinder = new BodyModelBinder(formatters, readerFactory, loggerFactory, options);
        }
示例#10
0
        private IReadOnlyList <ApiDescription> GetApiDescriptions()
        {
            var context = new ApiDescriptionProviderContext(_actionDescriptors);

            var options = new MvcOptions();
            var cfg     = JsonSerializerSettingsProvider.CreateSerializerSettings();
            var apool   = ArrayPool <char> .Shared;
            var opool   = new DefaultObjectPoolProvider();

            options.InputFormatters.Add(new JsonInputFormatter(new Mock <ILogger>().Object, cfg, apool, opool));
            options.OutputFormatters.Add(new JsonOutputFormatter(cfg, apool));

            var optionsAccessor = new Mock <IOptions <MvcOptions> >();

            optionsAccessor.Setup(o => o.Value).Returns(options);

            var constraintResolver = new Mock <IInlineConstraintResolver>();

            constraintResolver.Setup(i => i.ResolveConstraint("int")).Returns(new IntRouteConstraint());

            var provider = new DefaultApiDescriptionProvider(
                optionsAccessor.Object,
                constraintResolver.Object,
                CreateDefaultProvider()
                );

            provider.OnProvidersExecuting(context);
            provider.OnProvidersExecuted(context);
            return(new ReadOnlyCollection <ApiDescription>(context.Results));
        }
示例#11
0
        private DateTimeInputFormatterJson CreateCustomFormatter()
        {
            var inputSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            var jsonInputLogger = loggerFactory.CreateLogger <JsonInputFormatter>();

            return(new DateTimeInputFormatterJson(jsonInputLogger, inputSettings, charPool, objectPoolProvider));
        }
 public LocalizationAdminController(IDbResourceDataManager manager, IHostingEnvironment hostingEnvironment,
                                    DbResourceConfiguration configuration, JavaScriptResourceHandler javaScriptResourceHandler)
 {
     this.manager                            = manager;
     this.hostingEnvironment                 = hostingEnvironment;
     this.configuration                      = configuration;
     this.javaScriptResourceHandler          = javaScriptResourceHandler;
     jsonSerializerSettings                  = JsonSerializerSettingsProvider.CreateSerializerSettings();
     jsonSerializerSettings.ContractResolver = new DefaultContractResolver();
 }
示例#13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region service registration

            services.AddTransient <IMembersService, MembersService>();
            services.AddTransient <ILoginService, LoginService>();
            services.AddTransient <ITaskService, TaskService>();
            services.AddTransient <ITaskGroupService, TaskGroupService>();
            services.AddTransient <IProjectService, ProjectService>();
            services.AddTransient <IReportService, ReportService>();

            #endregion service registration

            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("TAIDatabase")));

            services.AddSession();
            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(new StatusCodeExceptionAttribute());
                options.Filters.Add(new WebServiceExceptionAttribute());
                options.OutputFormatters.Clear();

                var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();
                formatterSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

                var formatter = new JsonOutputFormatter(formatterSettings, ArrayPool <Char> .Create());
                options.OutputFormatters.Add(formatter);
            });
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                });
            });
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("pl-PL")
                };

                options.SupportedCultures   = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });
        }
示例#14
0
        public JsonHalOutputFormatter(IEnumerable <string> halJsonMediaTypes = null)
        {
            if (halJsonMediaTypes == null)
            {
                halJsonMediaTypes = new string[] { HalJsonType }
            }
            ;

            this.serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            this.jsonFormatter = new JsonOutputFormatter(this.serializerSettings, ArrayPool <Char> .Create());

            this.halJsonMediaTypes = halJsonMediaTypes;
        }
示例#15
0
        public override Task ExecuteResultAsync(ActionContext context)
        {
            //if (!context.IsChildAction)
            //{
            //    if (StatusCode.HasValue)
            //    {
            //        context.HttpContext.Response.StatusCode = StatusCode.Value;
            //    }
            //    context.HttpContext.Response.ContentType = "application/json";
            //    context.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            //}
            var settings = Settings ?? JsonSerializerSettingsProvider.CreateSerializerSettings();

            return(context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(Data, settings)));
        }
示例#16
0
        public JsonResult Get(string id)
        {
            var client = _repo.GetConnection(id);

            if (client == null)
            {
                throw new Exception("Device not found");
            }

            var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            settings.NullValueHandling = NullValueHandling.Ignore;

            return(new JsonResult(SpecGenerator.CompileData(client.GetProfile()), settings));
        }
示例#17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var outputSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            services
            .AddOptions()
            .Configure <AppSettings>(Configuration)
            .AddMvc()
            .AddMvcOptions(c => {
                c.OutputFormatters.Add(new JsonHalOutputFormatter(
                                           outputSettings,
                                           halJsonMediaTypes: new string[] { "application/hal+json", "application/vnd.example.hal+json", "application/vnd.example.hal.v1+json" }
                                           ));
            });
        }
        public MvcOptionsExtensionsTest()
        {
            testSubject = new MvcOptions();

            var serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            testSubject.InputFormatters.Add(
                new JsonInputFormatter(new Mock <ILogger>().Object,
                                       serializerSettings,
                                       ArrayPool <char> .Shared,
                                       new Mock <ObjectPoolProvider>().Object));

            testSubject.OutputFormatters.Add(
                new JsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared));
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            formatterSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            formatterSettings.ContractResolver      = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            JsonOutputFormatter formatter = new JsonOutputFormatter(formatterSettings, System.Buffers.ArrayPool <char> .Shared);

            services.Configure <MvcOptions>(options =>
            {
                options.OutputFormatters.RemoveType <JsonOutputFormatter>();
                options.OutputFormatters.Insert(0, formatter);
            });

            // Autofac & AdaptiveClient
            string fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "EndPoints.json");
            IEnumerable <IEndPointConfiguration> endPoints = EndPointUtilities.LoadEndPoints(fileName);
            string fileRoot = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            KanbanTasker.Services.ConnectionstringUtility.PopulateConnectionStrings(fileRoot, endPoints);

            ContainerBuilder builder = new ContainerBuilder();

            builder.Populate(services);
            builder.RegisterModule(new LeaderAnalytics.AdaptiveClient.EntityFrameworkCore.AutofacModule());
            builder.RegisterModule(new Services.AutofacModule());
            RegistrationHelper registrationHelper = new RegistrationHelper(builder);

            registrationHelper
            .RegisterEndPoints(endPoints)
            .RegisterModule(new KanbanTasker.Services.AdaptiveClientModule());

            var container = builder.Build();
            IDatabaseUtilities databaseUtilities = container.Resolve <IDatabaseUtilities>();

            // Create all databases or apply migrations

            foreach (IEndPointConfiguration ep in endPoints.Where(x => x.EndPointType == EndPointType.DBMS))
            {
                Task.Run(() => databaseUtilities.CreateOrUpdateDatabase(ep)).Wait();
            }

            return(container.Resolve <IServiceProvider>());
        }
示例#20
0
        public void ConfigureServices(IServiceCollection serviceCollection)
        {
            var jsonSerializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            var jsonOutputFormatter = new JsonOutputFormatter(jsonSerializerSettings, System.Buffers.ArrayPool <char> .Create());

            serviceCollection.AddNodeServices(options => {
                // options.LaunchWithDebugging = true;
                // options.DebuggingPort = 5858;
                options.HostingModel = NodeHostingModel.Socket;
                options.ProjectPath  = Path.Combine(Directory.GetCurrentDirectory(), "client");
            });

            serviceCollection.AddMvc(options =>
                                     options.OutputFormatters.Insert(0, jsonOutputFormatter));
            serviceCollection.AddSingleton <IEntitiesRepositoryFactory>(new EntitiesRepositoryFactory());
        }
示例#21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();
                formatterSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                formatterSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                formatterSettings.NullValueHandling          = NullValueHandling.Ignore;
                formatterSettings.Formatting = Formatting.Indented;

                var jsonOutputFormatter = new JsonOutputFormatter(formatterSettings, ArrayPool <Char> .Shared);

                config.OutputFormatters.RemoveType <JsonOutputFormatter>();
                config.OutputFormatters.Insert(0, jsonOutputFormatter);
            });

            services.AddMvc();
        }
示例#22
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context?.Result == null)
            {
                return;
            }

            var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            settings.ContractResolver = new IgnoreAllExceptContractResolver()
                                        .IgnoreAll(Ignored)
                                        .Except(Ignored, Except);

            var formatter = new JsonOutputFormatter(settings, ArrayPool <Char> .Shared);
            var result    = context.Result as ObjectResult;

            result.Formatters.Add(formatter);
        }
示例#23
0
        /// <summary>
        /// Configures and adds services to the container. This method gets called by the runtime.
        /// </summary>
        /// <param name="services">The service collection of <see cref="IServiceCollection" /> type.</param>
        /// <returns>The instance of <see cref="IServiceProvider"/>.</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDependencies();
            services.Configure(this.Configuration);

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.AddMvc(options =>
            {
                options.OutputFormatters.RemoveType <JsonOutputFormatter>();
                options.OutputFormatters.Add(new HomeCloudJsonOutputFormatter(
                                                 JsonSerializerSettingsProvider.CreateSerializerSettings(),
                                                 ArrayPool <char> .Shared));

                options.InputFormatters.Add(new HomeCloudMultipartFormDataInputFormatter());
            });

            return(services.BuildServiceProvider());
        }
        public static ObjectResult GenerateErrorResponse(CodeLabException codelabExp)
        {
            List <CodeLabException> allErrors = new List <CodeLabException>();

            allErrors.Add(codelabExp);

            ObjectResult res = new ObjectResult(allErrors);

            res.ContentTypes.Add("application/json");

            var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            formatterSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            JsonOutputFormatter formatter = new JsonOutputFormatter(formatterSettings, ArrayPool <Char> .Create());

            res.Formatters.Add(formatter);
            res.StatusCode = 490;
            return(res);
        }
示例#25
0
        public async Task StartFullSampleServer_GetUsers_VerifyResultContainsUsers()
        {
            // Arrange
            var server = new TestServer(Program.CreateWebHostBuilder());

            HttpClient client = server.CreateClient();

            // Act
            var response = await client.GetAsync("/users");

            response.EnsureSuccessStatusCode();

            string responseData = await response.Content.ReadAsStringAsync();

            // Assert
            response.StatusCode.Should().Be(200);
            response.Content.Headers.ContentType.MediaType.Should().Be("application/json");
            responseData.Should().Be(JsonConvert.SerializeObject(Program.Users, JsonSerializerSettingsProvider.CreateSerializerSettings()));
        }
        public async Task StartServerWithGetMethod_GetUsers_VerifyResultContainsUsers()
        {
            // Arrange
            var server = new TestServer(new WebHostBuilder()
                                        .ConfigureServices(s => s.AddRouting().AddMicroService(b => b.AddJson()).BuildServiceProvider())
                                        .Configure(app => app.Route("users").Get(Program.Users).Use()));

            HttpClient client = server.CreateClient();

            // Act
            var response = await client.GetAsync("/users");

            response.EnsureSuccessStatusCode();

            string responseData = await response.Content.ReadAsStringAsync();

            // Assert
            response.StatusCode.Should().Be(200);
            response.Content.Headers.ContentType.MediaType.Should().Be("application/json");
            responseData.Should().Be(JsonConvert.SerializeObject(Program.Users, JsonSerializerSettingsProvider.CreateSerializerSettings()));
        }
示例#27
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Starting Magda Reregistrations");

            JsonConvert.DefaultSettings =
                () => JsonSerializerSettingsProvider.CreateSerializerSettings().ConfigureForOrganisationRegistry();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{Environment.MachineName.ToLowerInvariant()}.json", optional: true)
                          .AddEnvironmentVariables();

            var configuration = builder.Build();

            var app = ConfigureServices(configuration);

            var logger = app.GetService <ILogger <Program> >();

            await RunProgram(logger, app);
        }
        public JsonHalOutputFormatter(
#if NET6_0
            MvcOptions mvcOpt,
#endif
            IEnumerable <string> halJsonMediaTypes = null)
        {
            if (halJsonMediaTypes == null)
            {
                halJsonMediaTypes = new string[] { HalJsonType }
            }
            ;

            serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            this.jsonFormatter = new JsonOutputFormatter(serializerSettings, ArrayPool <Char> .Create()
#if NET6_0
                                                         , mvcOpt, null
#endif
                                                         );

            this.halJsonMediaTypes = halJsonMediaTypes;
        }
示例#29
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context == null || context.Result == null || context.Result.GetType() != typeof(Microsoft.AspNetCore.Mvc.OkObjectResult))
            {
                return;
            }

            var settings = JsonSerializerSettingsProvider.CreateSerializerSettings();

            if (formatName == "camel")
            {
                settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            }
            else
            {
                settings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            }

            var formatter = new JsonOutputFormatter(settings, ArrayPool <Char> .Shared);

            (context.Result as Microsoft.AspNetCore.Mvc.OkObjectResult).Formatters.Add(formatter);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting Agentschap Zorg en Gezondheid FTP Dump");

            JsonConvert.DefaultSettings =
                () => JsonSerializerSettingsProvider.CreateSerializerSettings().ConfigureForOrganisationRegistry();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{Environment.MachineName.ToLowerInvariant()}.json", optional: true)
                          .AddEnvironmentVariables();

            var sqlConfiguration = builder.Build().GetSection(ConfigurationDatabaseConfiguration.Section).Get <ConfigurationDatabaseConfiguration>();
            var configuration    = builder
                                   .AddEntityFramework(x => x.UseSqlServer(
                                                           sqlConfiguration.ConnectionString,
                                                           y => y.MigrationsHistoryTable("__EFMigrationsHistory", WellknownSchemas.BackofficeSchema)))
                                   .Build();

            RunProgram <Runner>(configuration);
        }