/// <summary>
        /// Adds customized JSON serializer settings.
        /// </summary>
        public static IMvcCoreBuilder AddCustomJsonOptions(
            this IMvcCoreBuilder builder,
            IHostingEnvironment hostingEnvironment) =>
        builder.AddJsonOptions(
            options =>
        {
            if (hostingEnvironment.IsDevelopment())
            {
                // Pretty print the JSON in development for easier debugging.
                options.SerializerSettings.Formatting = Formatting.Indented;
            }

            // Parse dates as DateTimeOffset values by default. You should prefer using DateTimeOffset over
            // DateTime everywhere. Not doing so can cause problems with time-zones.
            options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;

            // Output enumeration values as strings in JSON.
            options.SerializerSettings.Converters.Add(new StringEnumConverter());
        });
Exemplo n.º 2
0
 public static IMvcCoreBuilder ConfigureControllerFactories(this IMvcCoreBuilder mvcServiceBuilder,
                                                            Func <IServiceProvider, IControllerActivatorProvider> controllerActivatorProvider = null,
                                                            Func <IServiceProvider, IControllerActivator> controllerActivator             = null,
                                                            Func <IServiceProvider, IControllerFactoryProvider> controllerFactoryProvider = null,
                                                            Func <IServiceProvider, IControllerFactory> controllerFactory = null)
 {
     if (controllerActivatorProvider == null)
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton <IControllerActivatorProvider, ControllerActivatorProvider>());
     }
     else
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton(controllerActivatorProvider));
     }
     if (controllerActivator == null)
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Transient <IControllerActivator, DefaultControllerActivator>());
     }
     else
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Transient(controllerActivator));
     }
     if (controllerFactoryProvider == null)
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton <IControllerFactoryProvider, ControllerFactoryProvider>());
     }
     else
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton(controllerFactoryProvider));
     }
     if (controllerFactory == null)
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton <IControllerFactory, DefaultControllerFactory>());
     }
     else
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton(controllerFactory));
     }
     //mvcServiceBuilder.AddControllersAsServices();
     //the line above does the following:
     //mvcServiceBuilder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
     return(mvcServiceBuilder);
 }
Exemplo n.º 3
0
        /// <summary>
        /// Registers <see cref="CookieTempDataProvider"/> as the default <see cref="ITempDataProvider"/> in the
        /// <see cref="IServiceCollection"/>. Also registers the default view services.
        /// </summary>
        /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
        /// <param name="setupAction">
        /// An <see cref="Action{CookieTempDataProviderOptions}"/> to configure the provided
        /// <see cref="CookieTempDataProviderOptions"/>.
        /// </param>
        /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
        public static IMvcCoreBuilder AddCookieTempDataProvider(
            this IMvcCoreBuilder builder,
            Action <CookieTempDataProviderOptions> setupAction)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            AddCookieTempDataProvider(builder);
            builder.Services.Configure(setupAction);

            return(builder);
        }
Exemplo n.º 4
0
        public static IMvcCoreBuilder AddViews(
            this IMvcCoreBuilder builder,
            Action <MvcViewOptions> setupAction)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            AddViews(builder);
            builder.Services.Configure(setupAction);

            return(builder);
        }
Exemplo n.º 5
0
        private IWebHostBuilder SetupWebHost(StringWriter testOutput)
        {
            var hostBuilder = new WebHostBuilder();

            // Configure services
#if ASPNETCORE2_0
            hostBuilder.UseLogJam((LogManagerConfig config, WebHostBuilderContext hostBuilderContext) =>
#else
            hostBuilder.UseLogJam((LogManagerConfig config, IServiceProvider serviceProvider) =>
#endif
            {
                config.UseTestOutput(_testOutput);
                config.UseTextWriter(testOutput);
            });

            hostBuilder.ConfigureServices(serviceCollection =>
            {
                IMvcCoreBuilder mvcCoreBuilder = serviceCollection.AddMvcCore();
                mvcCoreBuilder.AddJsonFormatters();
#if ASPNETCORE2_0
                serviceCollection.Configure <LoggerFilterOptions>(filterOptions => filterOptions.MinLevel = LogLevel.Trace);
#else
                serviceCollection.Configure <FilterLoggerSettings>(filterSettings => filterSettings.Add("Default", LogLevel.Trace));
#endif
            });

            // Configure webapp
            hostBuilder.Configure(appBuilder =>
            {
                appBuilder.UseStatusCodePages();
                appBuilder.UseExceptionHandler(new ExceptionHandlerOptions()
                {
                    ExceptionHandler = async context =>
                    {
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("Unhandled exception");
                    }
                });
                appBuilder.UseMvc();
            });

            return(hostBuilder);
        }
Exemplo n.º 6
0
        public static IMvcCoreBuilder AddModularRazorPages(this IMvcCoreBuilder builder)
        {
            builder.AddRazorPages(options =>
            {
                options.RootDirectory = "/";
                options.Conventions.Add(new DefaultModularPageRouteModelConvention());
            });

            builder.Services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <RazorViewEngineOptions>, ModularPageRazorViewEngineOptionsSetup>());

            builder.Services.TryAddEnumerable(
                ServiceDescriptor.Singleton <IPageApplicationModelProvider, ModularPageApplicationModelProvider>());

            builder.Services.Replace(
                ServiceDescriptor.Singleton <IActionDescriptorChangeProvider, ModularPageActionDescriptorChangeProvider>());

            return(builder);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Add Salesforce WebHook configuration and services to the specified <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IMvcCoreBuilder" /> to configure.</param>
        /// <returns>The <paramref name="builder"/>.</returns>
        public static IMvcCoreBuilder AddSalesforceWebHooks(this IMvcCoreBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var services = builder.Services;

            services.TryAddEnumerable(ServiceDescriptor.Singleton <IWebHookMetadata, SalesforceMetadata>());
            services.TryAddSingleton <ISalesforceResultCreator, SalesforceResultCreator>();

            // ??? Are the [DataContract] formatters also needed? XmlSerializer is enough for at least XElement.
            // ??? Does SalesforceAcknowledgmentFilter need a non-default Order too?
            return(builder
                   .AddXmlSerializerFormatters()
                   .AddWebHooks(OptionsSetupAction)
                   .AddSingletonFilter <SalesforceAcknowledgmentFilter>()
                   .AddSingletonFilter <SalesforceVerifyOrganizationIdFilter>(WebHookSecurityFilter.Order));
        }
Exemplo n.º 8
0
        public static IWebHostBuilder ForFullNode(this IWebHostBuilder hostBuilder, FullNode fullNode)
        {
            hostBuilder.ConfigureServices(s =>
            {
                IMvcCoreBuilder mvcBuilder = s.AddMvcCore(o =>
                {
                    o.ModelBinderProviders.Insert(0, new DestinationModelBinder());
                    o.ModelBinderProviders.Insert(0, new MoneyModelBinder());
                });

                // Include all feature assemblies for action discovery otherwise RPC actions will not execute
                // https://stackoverflow.com/questions/37725934/asp-net-core-mvc-controllers-in-separate-assembly
                foreach (Assembly assembly in fullNode.Services.Features.OfType <FullNodeFeature>().Select(x => x.GetType().GetTypeInfo().Assembly).Distinct())
                {
                    mvcBuilder.AddApplicationPart(assembly);
                }
            });

            return(hostBuilder);
        }
Exemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ConfigurationContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("connectionstring")));

            this.ApplicationService(services);
            this.ConfigureAuth(services);
            services.AddOptions();
            IMvcCoreBuilder mvcCoreBuilder = services.AddMvcCore(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            mvcCoreBuilder.AddFormatterMappings()
            .AddJsonFormatters()
            .AddCors();
        }
Exemplo n.º 10
0
        public static IMvcCoreBuilder AddJsonFormatters(
            this IMvcCoreBuilder builder,
            Action <JsonSerializerSettings> setupAction)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            AddJsonFormatterServices(builder.Services);

            builder.Services.Configure <MvcJsonOptions>((options) => setupAction(options.SerializerSettings));

            return(builder);
        }
Exemplo n.º 11
0
        private static void ConfigureInterfaces(this IMvcCoreBuilder mvcBuilder, IEnumerable <Type> serviceTypes)
        {
            foreach (var t in serviceTypes)
            {
                mvcBuilder.AddMvcOptions(opt =>
                {
                    opt.Conventions.Add(new ControllerModelConvention(t));
                    opt.Conventions.Add(new ActionModelConvention(t));
                    opt.Conventions.Add(new ParameterModelConvention(t));
                });
            }

            mvcBuilder.ConfigureApplicationPartManager(manager =>
            {
                var featureProvider = new ServiceControllerFeatureProvider(serviceTypes);

                manager.FeatureProviders.Remove(manager.FeatureProviders.FirstOrDefault(x => x.GetType() == typeof(ControllerFeatureProvider)));
                manager.FeatureProviders.Add(featureProvider);
            });
        }
Exemplo n.º 12
0
        public static IMvcCoreBuilder ConfigureMvcUsing(this IMvcCoreBuilder mvcCoreBuilder, ModuleRegistry moduleRegistry)
        {
            var controllerTypes = new List <Type>();

            var controllerToModulePrefixMap = new Dictionary <Type, BaseRoute>();

            foreach (var module in moduleRegistry.Modules)
            {
                var moduleControllerTypes = module.ControllerTypes;
                foreach (var moduleControllerType in moduleControllerTypes)
                {
                    controllerToModulePrefixMap.Add(moduleControllerType, module.BaseRoute);
                    controllerTypes.Add(moduleControllerType);
                }
            }

            return(mvcCoreBuilder
                   .AddMvcOptions(o => o.Conventions.Insert(0, new ModulePrefixConvention(controllerToModulePrefixMap)))
                   .AddSpecificControllers(controllerTypes));
        }
Exemplo n.º 13
0
        public static IMvcCoreBuilder AddCustomMvcOptions(
            this IMvcCoreBuilder builder,
            IHostingEnvironment hostingEnvironment) =>
        builder.AddMvcOptions(
            options =>
        {
            // Controls how controller actions cache content from the appsettings.json file.
            var cacheProfileOptions = builder.Services.BuildServiceProvider().GetRequiredService <CacheProfileOptions>();
            foreach (var keyValuePair in cacheProfileOptions)
            {
                options.CacheProfiles.Add(keyValuePair);
            }

            // Remove string and stream output formatters. These are not useful for an API serving JSON or XML.
            options.OutputFormatters.RemoveType <StreamOutputFormatter>();
            options.OutputFormatters.RemoveType <StringOutputFormatter>();

            // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid.
            options.ReturnHttpNotAcceptable = true;
        });
        public static IServiceCollection AddJsonApi <TContext>(this IServiceCollection services,
                                                               Action <JsonApiOptions> options,
                                                               IMvcCoreBuilder mvcBuilder) where TContext : DbContext
        {
            var config = new JsonApiOptions();

            options(config);

            config.BuildContextGraph(builder => builder.AddDbContext <TContext>());

            mvcBuilder
            .AddMvcOptions(opt =>
            {
                opt.Filters.Add(typeof(JsonApiExceptionFilter));
                opt.SerializeAsJsonApi(config);
            });

            AddJsonApiInternals <TContext>(services, config);
            return(services);
        }
        public static IServiceCollection AddJsonApi(
            this IServiceCollection services,
            Action <JsonApiOptions> configureOptions,
            IMvcCoreBuilder mvcBuilder,
            Action <ServiceDiscoveryFacade> autoDiscover = null)
        {
            var config = new JsonApiOptions();

            configureOptions(config);

            if (autoDiscover != null)
            {
                var facade = new ServiceDiscoveryFacade(services, config.ResourceGraphBuilder);
                autoDiscover(facade);
            }

            mvcBuilder.AddMvcOptions(opt => AddMvcOptions(opt, config));

            AddJsonApiInternals(services, config);
            return(services);
        }
Exemplo n.º 16
0
        public static IServiceProvider ConfigureApplicationServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment hostingEnvironment)
        {
            //add Config configuration parameters
            CepresConfig config = services.ConfigureStartupConfig <CepresConfig>(configuration.GetSection("Cepres"));

            //add accessor to HttpContext
            services.AddHttpContextAccessor();

            CommonHelper.DefaultFileProvider = new FileManagerProvider(hostingEnvironment);

            IMvcCoreBuilder mvcCoreBuilder = services.AddMvcCore();

            //create, initialize and configure the engine
            IEngine          engine          = EngineContext.Create();
            IServiceProvider serviceProvider = engine.ConfigureServices(services, configuration);

            SqlServerDataProvider.InitializeDatabase(config.DataConnectionString);


            return(serviceProvider);
        }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IMvcCoreBuilder builder = services
                                      .AddMvcCore()
                                      .AddApiExplorer()
                                      .AddAuthorization()
                                      .AddCors()
                                      .AddDataAnnotations()
                                      .AddFormatterMappings()
                                      .AddViews()
                                      .AddRazorViewEngine()
                                      .AddCacheTagHelper();

            AddTagHelpersFrameworkParts(builder.PartManager);

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Exemplo n.º 18
0
 public static IMvcCoreBuilder ConfigureActionInvokers(this IMvcCoreBuilder mvcServiceBuilder, Func <IServiceProvider, IActionInvokerFactory> actionInvokerFactory = null, Func <IServiceProvider, IActionInvokerProvider> actionInvokerProvider = null)
 {
     if (actionInvokerFactory == null)
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton <IActionInvokerFactory, ActionInvokerFactory>());
     }
     else
     {
         mvcServiceBuilder.Services.Replace(ServiceDescriptor.Singleton(actionInvokerFactory));
     }
     mvcServiceBuilder.Services.RemoveAll <IActionInvokerProvider>();
     if (actionInvokerProvider == null)
     {
         mvcServiceBuilder.Services.TryAddEnumerable(ServiceDescriptor.Transient <IActionInvokerProvider, ControllerActionInvokerProvider>());
     }
     else
     {
         mvcServiceBuilder.Services.TryAddEnumerable(ServiceDescriptor.Transient(actionInvokerProvider));
     }
     return(mvcServiceBuilder);
 }
Exemplo n.º 19
0
        public static IMvcCoreBuilder AddGitLfs(this IMvcCoreBuilder builder)
        {
            builder.AddNewtonsoftJson();
            builder.AddApplicationPart(typeof(LfsConstants).GetTypeInfo().Assembly);
            builder.AddMvcOptions(options =>
            {
                options.Filters.Add(new ProducesAttribute(LfsConstants.LfsMediaType.MediaType.Buffer));
                options.Filters.Add(new TypeFilterAttribute(typeof(BasicAuthFilter)));

                foreach (InputFormatter input in options.InputFormatters.OfType <NewtonsoftJsonInputFormatter>())
                {
                    input.SupportedMediaTypes.Add(LfsConstants.LfsMediaType);
                }

                foreach (OutputFormatter output in options.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>())
                {
                    output.SupportedMediaTypes.Add(LfsConstants.LfsMediaType);
                }
            });
            return(builder);
        }
Exemplo n.º 20
0
        public static IMvcCoreBuilder AddConfigurationApi(this IMvcCoreBuilder mvcBuilder,
                                                          Action <ConfigurationApiOptions> configureAction = null)
        {
            if (configureAction != null)
            {
                mvcBuilder.Services.Configure <ConfigurationApiOptions>(o =>
                {
                    configureAction.Invoke(o);
                });
            }

            mvcBuilder.Services.AddValidOptions();
            mvcBuilder.Services.AddSaveOptions();

            mvcBuilder.Services.TryAddSingleton <ITypeResolver, ReflectionTypeResolver>();
            mvcBuilder.Services.AddSingleton <ConfigurationService>();

            mvcBuilder.AddActiveRoute <ConfigurationController, ConfigurationFeature, ConfigurationApiOptions>();

            return(mvcBuilder);
        }
Exemplo n.º 21
0
        private static IMvcCoreBuilder ConfigureInterfaces(this IMvcCoreBuilder mvcBuilder, WebApiProxyOptions options)
        {
            foreach (var t in options.RegisteredServices.Select(x => x.Value))
            {
                mvcBuilder.AddMvcOptions(opt =>
                {
                    opt.Conventions.Add(new ControllerModelConvention(t));
                    opt.Conventions.Add(new ActionModelConvention(t));
                    opt.Conventions.Add(new ParameterModelConvention(t));
                });
            }

            mvcBuilder.ConfigureApplicationPartManager(manager =>
            {
                var featureProvider = new ServiceControllerFeatureProvider(options.RegisteredServices.Select(x => x.Value));
                manager.FeatureProviders.Remove(manager.FeatureProviders.FirstOrDefault(x => x.GetType() == typeof(ControllerFeatureProvider)));
                manager.FeatureProviders.Add(featureProvider);
            });

            return(mvcBuilder);
        }
        /// <summary>
        /// Adds an initialization callback for a given <typeparamref name="TTagHelper"/>.
        /// </summary>
        /// <remarks>
        /// The callback will be invoked on any <typeparamref name="TTagHelper"/> instance before the
        /// <see cref="ITagHelperComponent.ProcessAsync(TagHelperContext, TagHelperOutput)"/> method is called.
        /// </remarks>
        /// <typeparam name="TTagHelper">The type of <see cref="ITagHelper"/> being initialized.</typeparam>
        /// <param name="builder">The <see cref="IMvcCoreBuilder"/> instance this method extends.</param>
        /// <param name="initialize">An action to initialize the <typeparamref name="TTagHelper"/>.</param>
        /// <returns>The <see cref="IMvcCoreBuilder"/> instance this method extends.</returns>
        public static IMvcCoreBuilder InitializeTagHelper <TTagHelper>(
            this IMvcCoreBuilder builder,
            Action <TTagHelper, ViewContext> initialize)
            where TTagHelper : ITagHelper
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (initialize == null)
            {
                throw new ArgumentNullException(nameof(initialize));
            }

            var initializer = new TagHelperInitializer <TTagHelper>(initialize);

            builder.Services.AddSingleton(typeof(ITagHelperInitializer <TTagHelper>), initializer);

            return(builder);
        }
Exemplo n.º 23
0
    /// <summary>
    /// Register services needed for Razor Pages.
    /// </summary>
    /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
    /// <param name="setupAction">The action to setup the <see cref="RazorPagesOptions"/>.</param>
    /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
    public static IMvcCoreBuilder AddRazorPages(
        this IMvcCoreBuilder builder,
        Action <RazorPagesOptions> setupAction)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (setupAction == null)
        {
            throw new ArgumentNullException(nameof(setupAction));
        }

        builder.AddRazorViewEngine();

        AddRazorPagesServices(builder.Services);

        builder.Services.Configure(setupAction);

        return(builder);
    }
Exemplo n.º 24
0
        internal static IMvcCoreBuilder AddAuthorization(this IMvcCoreBuilder @this, IConfiguration configuration)
        {
            var authConfig = configuration
                             .GetSection("authentication")
                             .Get <AuthConfiguration>();

            if (!authConfig.IsEnabled())
            {
                return(@this.AddAuthorization());
            }

            return(@this
                   .AddAuthorization(options =>
            {
                options.AddPolicy(AdminPolicy, builder => builder
                                  .RequireScope("hawk"));

                options.AddPolicy(ReadOnlyPolicy, builder => builder
                                  .RequireScope("hawk")
                                  .RequireScope("hawk.readonly"));
            }));
        }
        /// <summary>
        /// Enabling JsonApiDotNetCore using the EF Core DbContext to build the ResourceGraph.
        /// </summary>
        public static IServiceCollection AddJsonApi <TDbContext>(this IServiceCollection services,
                                                                 Action <JsonApiOptions> options            = null,
                                                                 Action <IServiceDiscoveryFacade> discovery = null,
                                                                 Action <IResourceGraphBuilder> resources   = null,
                                                                 IMvcCoreBuilder mvcBuilder = null)
            where TDbContext : DbContext
        {
            var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore());

            if (options != null)
            {
                application.ConfigureJsonApiOptions(options);
            }
            application.ConfigureMvc();
            if (discovery != null)
            {
                application.AutoDiscover(discovery);
            }
            application.ConfigureResources <TDbContext>(resources);
            application.ConfigureServices();
            return(services);
        }
Exemplo n.º 26
0
        public static IMvcCoreBuilder AddCustomMvcOptions(this IMvcCoreBuilder builder)
        {
            return(builder.AddMvcOptions(
                       options =>
            {
                // Controls how controller actions cache content from the appsettings.json file.
                CacheProfileOptionsDictionary cacheProfileOptions = builder
                                                                    .Services
                                                                    .BuildServiceProvider()
                                                                    .GetRequiredService <CacheProfileOptionsDictionary>();
                foreach (System.Collections.Generic.KeyValuePair <string, Microsoft.AspNetCore.Mvc.CacheProfile> keyValuePair in cacheProfileOptions)
                {
                    options.CacheProfiles.Add(keyValuePair);
                }

                MediaTypeCollection jsonInputFormatterMediaTypes = options
                                                                   .InputFormatters
                                                                   .OfType <JsonInputFormatter>()
                                                                   .First()
                                                                   .SupportedMediaTypes;
                MediaTypeCollection jsonOutputFormatterMediaTypes = options
                                                                    .OutputFormatters
                                                                    .OfType <JsonOutputFormatter>()
                                                                    .First()
                                                                    .SupportedMediaTypes;

                // Add RESTful JSON media type (application/vnd.restful+json) to the JSON input and output formatters.
                // See http://restfuljson.org/
                jsonInputFormatterMediaTypes.Insert(0, ContentType.RestfulJson);
                jsonOutputFormatterMediaTypes.Insert(0, ContentType.RestfulJson);

                // Remove string and stream output formatters. These are not useful for an API serving JSON or XML.
                options.OutputFormatters.RemoveType <StreamOutputFormatter>();
                options.OutputFormatters.RemoveType <StringOutputFormatter>();

                // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid.
                options.ReturnHttpNotAcceptable = true;
            }));
        }
Exemplo n.º 27
0
        /// <summary>
        ///     Adds Fluent Validation services to the specified
        ///     <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcBuilder" />.
        /// </summary>
        /// <returns>
        ///     An <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder" /> that can be used to further configure the
        ///     MVC services.
        /// </returns>
        public static IMvcCoreBuilder AddFluentValidation(this IMvcCoreBuilder mvcBuilder, Action <FluentValidationMvcConfiguration> configurationExpression = null)
        {
            var expr   = configurationExpression ?? delegate { };
            var config = new FluentValidationMvcConfiguration();

            expr(config);

            if (config.AssembliesToRegister.Count > 0)
            {
                RegisterTypes(config.AssembliesToRegister, mvcBuilder.Services);
            }

            RegisterServices(mvcBuilder.Services, config);
            // clear all model validation providers since fluent validation will be handling everything

            mvcBuilder.AddMvcOptions(
                options => {
                options.ModelValidatorProviders.Clear();
            });

            return(mvcBuilder);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Perform file deply
        /// </summary>
        /// <param name="plug">Plugin file info</param>
        /// <param name="applicationPartManager">Application part manager</param>
        /// <returns>Assembly</returns>
        private static Assembly AddApplicationPart(FileInfo plug, IMvcCoreBuilder mvcCoreBuilder, GrandConfig config)
        {
            if (plug.Directory == null || plug.Directory.Parent == null)
            {
                throw new InvalidOperationException("The plugin directory for the " + plug.Name + " file exists in a folder outside of the allowed grandnode folder hierarchy");
            }

            var _plug = config.PluginShadowCopy ? ShadowCopyFile(plug, Directory.CreateDirectory(_shadowCopyFolder.FullName)) : plug;

            try
            {
                Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(_plug.FullName);
                //we can now register the plugin definition
                Debug.WriteLine("Adding to ApplicationParts: '{0}'", assembly.FullName);
                mvcCoreBuilder.AddApplicationPart(assembly);
                return(assembly);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"The plugin directory for the {plug.Name} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {plug.FullName} - exception: {ex.Message}");
            }
        }
Exemplo n.º 29
0
        public static IMvcCoreBuilder AddCustomMvcOptions(
            this IMvcCoreBuilder builder,
            IHostingEnvironment hostingEnvironment) =>
        builder.AddMvcOptions(
            options =>
        {
            // Controls how controller actions cache content from the appsettings.json file.
            var cacheProfileOptions = builder
                                      .Services
                                      .BuildServiceProvider()
                                      .GetRequiredService <CacheProfileOptions>();
            foreach (var keyValuePair in cacheProfileOptions)
            {
                options.CacheProfiles.Add(keyValuePair);
            }

            var jsonInputFormatterMediaTypes = options
                                               .InputFormatters
                                               .OfType <JsonInputFormatter>()
                                               .First()
                                               .SupportedMediaTypes;
            var jsonOutputFormatterMediaTypes = options
                                                .OutputFormatters
                                                .OfType <JsonOutputFormatter>()
                                                .First()
                                                .SupportedMediaTypes;

            // Add Problem Details media type (application/problem+json) to the JSON output formatters.
            // See https://tools.ietf.org/html/rfc7807
            jsonOutputFormatterMediaTypes.Insert(0, ContentType.ProblemJson);

            // Add RESTful JSON media type (application/vnd.restful+json) to the JSON input and output formatters.
            // See http://restfuljson.org/
            jsonInputFormatterMediaTypes.Insert(0, ContentType.RestfulJson);
            jsonOutputFormatterMediaTypes.Insert(0, ContentType.RestfulJson);

            // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid.
            options.ReturnHttpNotAcceptable = true;
        });
Exemplo n.º 30
0
        public static IMvcCoreBuilder AddMessagePackFormatters(this IMvcCoreBuilder builder, Action <MessagePackFormatterOptions> messagePackFormatterOptionsConfiguration)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var messagePackFormatterOptions = new MessagePackFormatterOptions();

            messagePackFormatterOptionsConfiguration?.Invoke(messagePackFormatterOptions);

            messagePackFormatterOptions.Options.WithResolver(messagePackFormatterOptions.FormatterResolver);


            foreach (var extension in messagePackFormatterOptions.SupportedExtensions)
            {
                foreach (var contentType in messagePackFormatterOptions.SupportedContentTypes)
                {
                    builder.AddFormatterMappings(m => m.SetMediaTypeMappingForFormat(extension, new MediaTypeHeaderValue(contentType)));
                }
            }

            //builder.AddMvcOptions(options => options.InputFormatters.Add(new MessagePackInputFormatter(messagePackFormatterOptions)));
            //builder.AddMvcOptions(options => options.OutputFormatters.Add(new MessagePackOutputFormatter(messagePackFormatterOptions)));

            builder.AddMvcOptions(options =>
            {
                options.InputFormatters.Clear();
                options.InputFormatters.Add(new MessagePackInputFormatter(messagePackFormatterOptions));
            });
            builder.AddMvcOptions(options =>
            {
                options.OutputFormatters.Clear();
                options.OutputFormatters.Add(new MessagePackOutputFormatter(messagePackFormatterOptions));
            });

            return(builder);
        }