Exemplo n.º 1
0
        // This method gets called by the runtime.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<MoviesDbContext>();

            // Add MVC services to the services container.
            services.AddMvc().Configure<MvcOptions>(options =>
			{
				int position = options.OutputFormatters.FindIndex(f =>
									  f.Instance is JsonOutputFormatter);

				var settings = new JsonSerializerSettings()
				{
					ContractResolver = new CamelCasePropertyNamesContractResolver()
				};
				var formatter = new JsonOutputFormatter();
				formatter.SerializerSettings = settings;

				options.OutputFormatters.Insert(position, formatter);
			});

            // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
            // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
            // services.AddWebApiConventions();

        }
Exemplo n.º 2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().Configure<MvcOptions>(options =>
            {
                var jsonFormatter = new JsonOutputFormatter
                {
                    SerializerSettings =
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    }
                };

                options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
                options.OutputFormatters.Insert(0, jsonFormatter);

            });

            services.AddTransient<IContactsRepository, ContactsRepository>();

            services.ConfigureCors(options =>
            {
                options.AddPolicy(
                    "CorsTutaureliaNet",
                    builder =>
                    {
                        builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
                    });
            });
        }
Exemplo n.º 3
0
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<TemplateContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddMvc().Configure<MvcOptions>(options =>
            {
                // Support Camelcasing in MVC API Controllers
                int position = options.OutputFormatters.ToList().FindIndex(f => f is JsonOutputFormatter);

                var formatter = new JsonOutputFormatter()
                {
                    SerializerSettings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }
                };

                options.OutputFormatters.Insert(position, formatter);
            });

            ConfigureRepositories(services);
        }
Exemplo n.º 4
0
        public JsonResult CustomFormatter()
        {
            var formatter = new JsonOutputFormatter();
            formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            return new JsonResult(new { Message = "hello" }, formatter);
        }
Exemplo n.º 5
0
        public JsonResult CustomContentType()
        {
            var formatter = new JsonOutputFormatter();
            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/message+json"));

            var result = new JsonResult(new { Message = "hello" }, formatter);
            result.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/message+json"));
            return result;
        }
Exemplo n.º 6
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            var result = context.Result as ObjectResult;
            if (result != null)
            {
                result.Formatters.Add(new PlainTextFormatter());
                result.Formatters.Add(new CustomFormatter("application/custom"));

                var jsonFormatter = new JsonOutputFormatter();
                jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
                result.Formatters.Add(jsonFormatter);
            }

            base.OnActionExecuted(context);
        }
Exemplo n.º 7
0
        public override void ExecuteResult([NotNull] ActionContext context)
        {
            var response = context.HttpContext.Response;
            var writeStream = response.Body;

            if (response.ContentType == null)
            {
                response.ContentType = "application/json";
            }

            using (var writer = new StreamWriter(writeStream, Encoding, BufferSize, leaveOpen: true))
            {
                var formatter = new JsonOutputFormatter(SerializerSettings, Indent);
                formatter.WriteObject(writer, Data);
            }
        }
        public void Execute_SerializesData_UsingSpecifiedFormatter()
        {
            // Arrange
            var view = Mock.Of<IView>();
            var buffer = new MemoryStream();
            var viewComponentContext = GetViewComponentContext(view, buffer);

            var expectedFormatter = new JsonOutputFormatter();
            var result = new JsonViewComponentResult(1, expectedFormatter);

            // Act
            result.Execute(viewComponentContext);
            buffer.Position = 0;

            // Assert
            Assert.Equal(expectedFormatter, result.Formatter);
            Assert.Equal("1", new StreamReader(buffer).ReadToEnd());
        }
Exemplo n.º 9
0
        public IActionResult ReturnsIndentedJson()
        {
            var user = new User()
            {
                Id = 1,
                Alias = "john",
                description = "Administrator",
                Designation = "Administrator",
                Name = "John Williams"
            };

            var jsonFormatter = new JsonOutputFormatter();
            jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

            var objectResult = new ObjectResult(user);
            objectResult.Formatters.Add(jsonFormatter);

            return objectResult;
        }
Exemplo n.º 10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .Configure<MvcOptions>(options =>
                {
                    var jsonOutputFormatter = new JsonOutputFormatter
                    {
                        SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
                    };
                    options.OutputFormatters.Insert(0, jsonOutputFormatter);
                });

            services.AddCors();

            var builder = new ContainerBuilder();
            builder.RegisterModule(new AutofacModule(Configuration));
            builder.Populate(services);

            var container = builder.Build();
            return container.Resolve<IServiceProvider>();
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        public void Setup(MvcOptions options)
        {
            // Set up ViewEngines
            options.ViewEngines.Add(typeof(RazorViewEngine));

            // Set up ModelBinding
            options.ModelBinders.Add(new TypeConverterModelBinder());
            options.ModelBinders.Add(new TypeMatchModelBinder());
            options.ModelBinders.Add(new ByteArrayModelBinder());
            options.ModelBinders.Add(typeof(GenericModelBinder));
            options.ModelBinders.Add(new MutableObjectModelBinder());
            options.ModelBinders.Add(new ComplexModelDtoModelBinder());

            // Set up default output formatters.
            options.OutputFormatters.Add(new HttpNoContentOutputFormatter());
            options.OutputFormatters.Add(new TextPlainFormatter());
            options.OutputFormatters.Add(new JsonOutputFormatter(JsonOutputFormatter.CreateDefaultSettings(),
                                                                 indent: false));
            options.OutputFormatters.Add(
                new XmlDataContractSerializerOutputFormatter(XmlOutputFormatter.GetDefaultXmlWriterSettings()));
            options.OutputFormatters.Add(
                new XmlSerializerOutputFormatter(XmlOutputFormatter.GetDefaultXmlWriterSettings()));

            // Set up default input formatters.
            options.InputFormatters.Add(new JsonInputFormatter());
            options.InputFormatters.Add(new XmlSerializerInputFormatter());
            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());

            // Set up ValueProviders
            options.ValueProviderFactories.Add(new RouteValueValueProviderFactory());
            options.ValueProviderFactories.Add(new QueryStringValueProviderFactory());
            options.ValueProviderFactories.Add(new FormValueProviderFactory());

            // Set up validators
            options.ModelValidatorProviders.Add(new DataAnnotationsModelValidatorProvider());
            options.ModelValidatorProviders.Add(new DataMemberModelValidatorProvider());
        }
Exemplo n.º 12
0
        public async Task ExecuteResultAsync_UsesPassedInFormatter()
        {
            // Arrange
            var expected = Enumerable.Concat(Encoding.UTF8.GetPreamble(), _abcdUTF8Bytes);

            var context = GetHttpContext();
            var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());

            var formatter = new JsonOutputFormatter();
            formatter.SupportedEncodings.Clear();

            // This is UTF-8 WITH BOM
            formatter.SupportedEncodings.Add(Encoding.UTF8);

            var result = new JsonResult(new { foo = "abcd" }, formatter);

            // Act
            await result.ExecuteResultAsync(actionContext);
            var written = GetWrittenBytes(context);

            // Assert
            Assert.Equal(expected, written);
            Assert.Equal("application/json; charset=utf-8", context.Response.ContentType);
        }
Exemplo n.º 13
0
        public static IEnumerable <IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
        {
            var describe = new ServiceDescriber(configuration);

            yield return(describe.Transient <IOptionsSetup <MvcOptions>, MvcOptionsSetup>());

            yield return(describe.Transient <IControllerFactory, DefaultControllerFactory>());

            yield return(describe.Singleton <IControllerActivator, DefaultControllerActivator>());

            yield return(describe.Singleton <IActionSelectorDecisionTreeProvider, ActionSelectorDecisionTreeProvider>());

            yield return(describe.Scoped <IActionSelector, DefaultActionSelector>());

            yield return(describe.Transient <IActionInvokerFactory, ActionInvokerFactory>());

            yield return(describe.Transient <IControllerAssemblyProvider, DefaultControllerAssemblyProvider>());

            yield return(describe.Transient <IActionDiscoveryConventions, DefaultActionDiscoveryConventions>());

            // The host is designed to be discarded after consumption and is very inexpensive to initialize.
            yield return(describe.Transient <IMvcRazorHost, MvcRazorHost>());

            yield return(describe.Singleton <ICompilationService, RoslynCompilationService>());

            yield return(describe.Singleton <IRazorCompilationService, RazorCompilationService>());

            yield return(describe.Singleton <IViewEngineProvider, DefaultViewEngineProvider>());

            yield return(describe.Scoped <ICompositeViewEngine, CompositeViewEngine>());

            yield return(describe.Singleton <IViewStartProvider, ViewStartProvider>());

            yield return(describe.Transient <IRazorView, RazorView>());

            yield return(describe.Singleton <IRazorPageActivator, RazorPageActivator>());

            // Virtual path view factory needs to stay scoped so views can get get scoped services.
            yield return(describe.Scoped <IRazorPageFactory, VirtualPathRazorPageFactory>());

            yield return(describe.Singleton <IFileInfoCache, ExpiringFileInfoCache>());

            yield return(describe.Transient <INestedProvider <ActionDescriptorProviderContext>,
                                             ReflectedActionDescriptorProvider>());

            yield return(describe.Transient <INestedProvider <ActionInvokerProviderContext>,
                                             ReflectedActionInvokerProvider>());

            yield return(describe.Singleton <IActionDescriptorsCollectionProvider,
                                             DefaultActionDescriptorsCollectionProvider>());

            yield return(describe.Transient <IModelMetadataProvider, DataAnnotationsModelMetadataProvider>());

            yield return(describe.Scoped <IActionBindingContextProvider, DefaultActionBindingContextProvider>());

            yield return(describe.Transient <IInputFormatterSelector, DefaultInputFormatterSelector>());

            yield return(describe.Scoped <IInputFormattersProvider, DefaultInputFormattersProvider>());

            yield return(describe.Transient <IModelBinderProvider, DefaultModelBindersProvider>());

            yield return(describe.Scoped <ICompositeModelBinder, CompositeModelBinder>());

            yield return(describe.Transient <IValueProviderFactoryProvider, DefaultValueProviderFactoryProvider>());

            yield return(describe.Scoped <ICompositeValueProviderFactory, CompositeValueProviderFactory>());

            yield return(describe.Transient <IOutputFormattersProvider, DefaultOutputFormattersProvider>());

            yield return(describe.Instance <JsonOutputFormatter>(
                             new JsonOutputFormatter(JsonOutputFormatter.CreateDefaultSettings(), indent: false)));

            // The IGlobalFilterProvider is used to build the action descriptors (likely once) and so should
            // remain transient to avoid keeping it in memory.
            yield return(describe.Transient <IGlobalFilterProvider, DefaultGlobalFilterProvider>());

            yield return(describe.Transient <INestedProvider <FilterProviderContext>, DefaultFilterProvider>());

            yield return(describe.Transient <IModelValidatorProviderProvider, DefaultModelValidatorProviderProvider>());

            yield return(describe.Scoped <ICompositeModelValidatorProvider, CompositeModelValidatorProvider>());

            yield return(describe.Scoped <IUrlHelper, UrlHelper>());

            yield return(describe.Transient <IViewComponentSelector, DefaultViewComponentSelector>());

            yield return(describe.Singleton <IViewComponentActivator, DefaultViewComponentActivator>());

            yield return(describe.Transient <IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>());

            yield return(describe.Transient <INestedProvider <ViewComponentInvokerProviderContext>,
                                             DefaultViewComponentInvokerProvider>());

            yield return(describe.Transient <IViewComponentHelper, DefaultViewComponentHelper>());

            yield return(describe.Transient <IAuthorizationService, DefaultAuthorizationService>());

            yield return(describe.Singleton <IClaimUidExtractor, DefaultClaimUidExtractor>());

            yield return(describe.Singleton <AntiForgery, AntiForgery>());

            yield return(describe.Singleton <IAntiForgeryAdditionalDataProvider,
                                             DefaultAntiForgeryAdditionalDataProvider>());

            yield return
                (describe.Describe(
                     typeof(INestedProviderManager <>),
                     typeof(NestedProviderManager <>),
                     implementationInstance: null,
                     lifecycle: LifecycleKind.Transient));

            yield return
                (describe.Describe(
                     typeof(INestedProviderManagerAsync <>),
                     typeof(NestedProviderManagerAsync <>),
                     implementationInstance: null,
                     lifecycle: LifecycleKind.Transient));

            yield return(describe.Transient <IHtmlHelper, HtmlHelper>());

            yield return
                (describe.Describe(
                     typeof(IHtmlHelper <>),
                     typeof(HtmlHelper <>),
                     implementationInstance: null,
                     lifecycle: LifecycleKind.Transient));

            yield return(describe.Transient <MvcMarkerService, MvcMarkerService>());
        }
Exemplo n.º 14
0
 public JsonViewComponentResult([NotNull] object data)
 {
     Data = data;
     _jsonSerializerSettings = JsonOutputFormatter.CreateDefaultSettings();
 }
Exemplo n.º 15
0
 public static JsonOutputFormatter GetConfiguredOutputFormatter()
 {
     var formatter = new JsonOutputFormatter();
     ConfigureSerializer(formatter.SerializerSettings);
     return formatter;
 }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new <see cref="JsonViewComponentResult"/>.
 /// </summary>
 /// <param name="value">The value to format as JSON text.</param>
 /// <param name="formatter">The <see cref="JsonOutputFormatter"/> to use.</param>
 public JsonViewComponentResult(object value, JsonOutputFormatter formatter)
 {
     Value     = value;
     Formatter = formatter;
 }
Exemplo n.º 17
0
        public async Task ExecuteResultAsync_UsesPassedInFormatter_ContentTypeSpecified()
        {
            // Arrange
            var expected = _abcdUTF8Bytes;

            var context = GetHttpContext();
            var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());

            var formatter = new JsonOutputFormatter();
            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/hal+json"));

            var result = new JsonResult(new { foo = "abcd" }, formatter);
            result.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/hal+json"));

            // Act
            await result.ExecuteResultAsync(actionContext);
            var written = GetWrittenBytes(context);

            // Assert
            Assert.Equal(expected, written);
            Assert.Equal("application/hal+json; charset=utf-8", context.Response.ContentType);
        }
Exemplo n.º 18
0
 public void Execute([NotNull] ViewComponentContext context)
 {
     var formatter = new JsonOutputFormatter(SerializerSettings, Indent);
     formatter.WriteObject(context.Writer, Data);
 }
Exemplo n.º 19
0
        public void Execute([NotNull] ViewComponentContext context)
        {
            var formatter = new JsonOutputFormatter();

            formatter.WriteObject(context.Writer, Data);
        }
Exemplo n.º 20
0
        public async Task ExecuteResultAsync_UsesPassedInFormatter()
        {
            // Arrange
            var expected = _abcdUTF8Bytes;

            var context = GetHttpContext();
            var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor());

            var formatter = new JsonOutputFormatter();
            formatter.SupportedEncodings.Clear();

            // This is UTF-8 WITH BOM
            formatter.SupportedEncodings.Add(Encoding.UTF8);

            var result = new JsonResult(new { foo = "abcd" }, formatter);

            // Act
            await result.ExecuteResultAsync(actionContext);
            var written = GetWrittenBytes(context);

            // Assert
            Assert.Equal(expected, written);
            Assert.Equal("application/json; charset=utf-8", context.Response.ContentType);
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<NerdDinnerDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddScoped<INerdDinnerRepository, NerdDinnerRepository>();

            // Add Identity services to the services container.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<NerdDinnerDbContext>()
                .AddDefaultTokenProviders();

            services.ConfigureFacebookAuthentication(options =>
            {
                options.ClientId = Configuration["Authentication:Facebook:AppId"];
                options.ClientSecret = Configuration["Authentication:Facebook:AppSecret"];
            });

            services.ConfigureGoogleAuthentication(options =>
            {
                options.ClientId = Configuration["Authentication:Google:AppId"];
                options.ClientSecret = Configuration["Authentication:Google:AppSecret"];
            });

            services.ConfigureTwitterAuthentication(options =>
            {
                options.ConsumerKey = Configuration["Authentication:Twitter:AppId"];
                options.ConsumerSecret = Configuration["Authentication:Twitter:AppSecret"];
            });

            //services.ConfigureMicrosoftAccountAuthentication(options =>
            //{
            //    options.Caption = "MicrosoftAccount - Requires project changes";
            //    options.ClientId = Configuration["Authentication:Microsoft:AppId"];
            //    options.ClientSecret = Configuration["Authentication:Microsoft:AppSecret"];
            //});

            // Add MVC services to the services container.
            services.AddMvc().Configure<MvcOptions>(options =>
            {
                var settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };

                var formatter = new JsonOutputFormatter { SerializerSettings = settings };

               options.OutputFormatters.Insert(0, formatter);

                // Add validation filters
                options.Filters.Add(new ValidateModelFilterAttribute());
            });
        }
Exemplo n.º 22
0
        // This method gets called by the runtime.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
              services.AddEntityFramework()
              .AddSqlServer()
              .AddDbContext<MyCountriesContext>(options =>
              options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

              // Add Identity services to the services container.
              services.AddIdentity<ApplicationUser, IdentityRole>()
              .AddEntityFrameworkStores<MyCountriesContext>()
              .AddDefaultTokenProviders();

              // Add MVC services to the services container.
              services.AddMvc()
            .Configure<MvcOptions>(options =>
            {
              // See Strathweb's great discussion of formatters: http://www.strathweb.com/2014/11/formatters-asp-net-mvc-6/

              // Support Camelcasing in MVC API Controllers
              var jsonOutputFormatter = new JsonOutputFormatter();
              jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
              jsonOutputFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;

              //options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
              options.OutputFormatters.Insert(0, jsonOutputFormatter);
            }); ;

              // Add other services
              services.AddScoped<IMyCountriesRepository, MyCountriesRepository>();
            #if DEBUG
              services.AddScoped<IEmailer, ConsoleEmailer>();
            #else
              services.AddScoped<IEmailer, Emailer>();
            #endif
        }
 /// <summary>
 /// Initializes a new <see cref="JsonViewComponentResult"/>.
 /// </summary>
 /// <param name="value">The value to format as JSON text.</param>
 /// <param name="formatter">The <see cref="JsonOutputFormatter"/> to use.</param>
 public JsonViewComponentResult(object value, JsonOutputFormatter formatter)
 {
     Value = value;
     Formatter = formatter;
 }
Exemplo n.º 24
0
        public void Execute([NotNull] ViewComponentContext context)
        {
            var formatter = new JsonOutputFormatter(SerializerSettings, Indent);

            formatter.WriteObject(context.Writer, Data);
        }
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddMvc();

            services.AddCors();

            services.AddSwagger();

            services.ConfigureSwaggerSchema(o =>
            {
                o.DescribeAllEnumsAsStrings = true;
            });

            services.ConfigureSwaggerDocument(o =>
            {
                o.SingleApiVersion(new Info
                {
                    Version = "v1",
                    Title = "Film Industry Network API",
                    Description = "Documentation of the API for interfacing with the Film Industry Network",
                    TermsOfService = "Use at your own risk"
                });
            });

            services.AddRouting();

            services.AddSingleton<IContext, NetworkContext>();
            services.AddScoped<IPersonRepository, PersonRepository>();
            services.AddScoped<IMovieRepository, MovieRepository>();
            services.AddScoped<IPersonService, PersonService>();
            services.AddScoped<IMovieService, MovieService>();
            services.AddScoped<IGraphMovieService, GraphMovieService>();
            services.AddScoped<IGraphPersonService, GraphPersonService>();
            services.AddTransient<IDataCollectorFactory, DataCollectorFactory>();

            services.Configure<MvcOptions>(options =>
            {
                var settings = new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto
                };
                var jsonFormatter = options.OutputFormatters.Single(o => o.GetType() == typeof(JsonOutputFormatter));
                options.OutputFormatters.Remove(jsonFormatter);
                var outputFormatter = new JsonOutputFormatter { SerializerSettings = settings };
                options.OutputFormatters.Add(outputFormatter);
            });

            //services.AddWebApiConventions();
        }