Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
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));
        }
Ejemplo n.º 3
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());
        }
        // NOTE: This method was created to make sure to create a different instance of contract resolver as by default
        // MvcJsonOptions uses a static shared instance of resolver which when changed causes other tests to fail.
        private MvcNewtonsoftJsonOptions CreateDefaultMvcJsonOptions()
        {
            var options = new MvcNewtonsoftJsonOptions();

            options.SerializerSettings.ContractResolver = JsonSerializerSettingsProvider.CreateContractResolver();
            return(options);
        }
Ejemplo n.º 5
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));
        }
Ejemplo n.º 6
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"));
            //});
        }
Ejemplo n.º 7
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;
                };
            }));
        }
Ejemplo n.º 8
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" }));
            });
        }
        /// <summary>
        /// Add the default JSON serialization settings provider.
        /// </summary>
        /// <param name="services">The target service collection.</param>
        /// <param name="configurationCallback">Optional callback used to modify the <see cref="JsonSerializerSettings"/>.</param>
        /// <returns>The service collection.</returns>
        public static IServiceCollection AddJsonNetSerializerSettingsProvider(
            this IServiceCollection services,
            Action <IServiceProvider, JsonSerializerSettings>?configurationCallback = null)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (!services.Any(s => typeof(IJsonSerializerSettingsProvider).IsAssignableFrom(s.ServiceType)))
            {
                services.AddSingleton <IJsonSerializerSettingsProvider>(
                    sp =>
                {
                    IEnumerable <JsonConverter> converters = sp.GetServices <JsonConverter>();
                    var serializerSettingsProvider         = new JsonSerializerSettingsProvider(converters);

                    configurationCallback?.Invoke(sp, serializerSettingsProvider.Instance);

                    return(serializerSettingsProvider);
                });
            }
            else if (configurationCallback is not null)
            {
                throw new InvalidOperationException("Service configuration for IJsonSerializerSettingsProvider has already completed, so it is not possible to invoke the supplied configurationCallback");
            }

            return(services);
        }
Ejemplo n.º 10
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));
        }
Ejemplo n.º 11
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));
        }
Ejemplo n.º 12
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);
    }
Ejemplo n.º 13
0
        private DateTimeInputFormatterJson CreateCustomFormatter()
        {
            var inputSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();

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

            return(new DateTimeInputFormatterJson(jsonInputLogger, inputSettings, charPool, objectPoolProvider));
        }
        public static string Create(HttpContext context, BreadResponse response)
        {
            context.Response.ContentType = ContentTypeJson;

            string jsonResponse =
                JsonConvert.SerializeObject(response, JsonSerializerSettingsProvider.SerializerSettings());

            return(jsonResponse);
        }
 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();
 }
Ejemplo n.º 16
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;
            });
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Adds json support using supplied settings
        /// <para>Can create a deserializer for application/json, text/json, and text/javascript</para>
        /// </summary>
        /// <param name="builder">The builder</param>
        /// <param name="settings">Supplied JsonSerializerSettings</param>
        /// <returns>ISolidHttpCoreBuilder</returns>
        public static ISolidHttpCoreBuilder AddJson(this ISolidHttpCoreBuilder builder, JsonSerializerSettings settings)
        {
            var provider = new JsonSerializerSettingsProvider(settings);

            builder.Services.AddSingleton <IJsonSerializerSettingsProvider>(provider);
            builder.AddDeserializer <JsonResponseDeserializerFactory>("application/json", "text/json", "text/javascript");

            return(builder
                   .OnRequestCreated((services, request) =>
            {
                var p = services.GetRequiredService <IJsonSerializerSettingsProvider>();
                request.BaseRequest.Properties.Add("JsonSerializerSettings", p.GetJsonSerializerSettings());
            }));
        }
Ejemplo n.º 18
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;
        }
Ejemplo n.º 19
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));
        }
Ejemplo n.º 20
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)));
        }
Ejemplo n.º 21
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));
        }
Ejemplo n.º 23
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>());
        }
Ejemplo n.º 24
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());
        }
Ejemplo n.º 25
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();
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 29
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()));
        }
Ejemplo n.º 30
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);
        }