コード例 #1
0
 /// <summary>
 /// Configures the input and output formatters.
 /// </summary>
 private static void ConfigureFormatters(IMvcBuilder mvcBuilder)
 {
     // Configures the JSON output formatter to use camel case property names like 'propertyName' instead of 
     // pascal case 'PropertyName' as this is the more common JavaScript/JSON style.
     mvcBuilder.AddJsonOptions(
         x => x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
 }
コード例 #2
0
        /// <summary>
        /// Configures the input and output formatters.
        /// </summary>
        private static void ConfigureFormatters(IMvcBuilder mvcBuilder)
        {
            // The JSON input and output formatters are added to MVC by default.
            // $Start-JsonSerializerSettings$

            // Configures the JSON output formatter to use camel case property names like 'propertyName' instead of 
            // pascal case 'PropertyName' as this is the more common JavaScript/JSON style.
            mvcBuilder.AddJsonOptions(
                x => x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
            // $End-JsonSerializerSettings$
            // $Start-BsonFormatter$

            // Adds the BSON input and output formatters using the JSON.NET serializer.
            mvcBuilder.AddBsonSerializerFormatters();
            // $End-BsonFormatter$
            // $Start-XmlFormatter-DataContractSerializer$

            // Adds the XML input and output formatter using the DataContractSerializer.
            mvcBuilder.AddXmlDataContractSerializerFormatters();
            // $End-XmlFormatter-DataContractSerializer$
            // $Start-XmlFormatter-XmlSerializer$

            // Adds the XML input and output formatter using the XmlSerializer.
            mvcBuilder.AddXmlSerializerFormatters();
            // $End-XmlFormatter-XmlSerializer$
        }
コード例 #3
0
ファイル: Builder.cs プロジェクト: diqiucong/ZKEACMS.Core
        public static void UseZKEACMS(this IServiceCollection services, IConfiguration configuration)
        {
            IMvcBuilder mvcBuilder = services.AddMvc(option =>
            {
                option.ModelBinderProviders.Insert(0, new WidgetTypeModelBinderProvider());
                option.ModelMetadataDetailsProviders.Add(new DataAnnotationsMetadataProvider());
                //option.EnableEndpointRouting = false;
            })
                                     .AddControllersAsServices()
                                     .AddJsonOptions(option => { option.SerializerSettings.DateFormatString = "yyyy-MM-dd"; })
                                     .SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.TryAddScoped <IApplicationContextAccessor, ApplicationContextAccessor>();
            services.TryAddScoped <IApplicationContext, CMSApplicationContext>();
            services.TryAddSingleton <IRouteProvider, RouteProvider>();

            services.AddTransient <IRouteDataProvider, PaginationRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, PostIdRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, CategoryRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, HtmlRouteDataProvider>();

            services.TryAddSingleton <IAdminMenuProvider, AdminMenuProvider>();
            services.TryAddTransient <IWidgetActivator, DefaultWidgetActivator>();
            services.TryAddTransient <ICarouselItemService, CarouselItemService>();
            services.TryAddTransient <ICarouselService, CarouselService>();
            services.TryAddTransient <INavigationService, NavigationService>();

            services.TryAddTransient <IDashboardProviderService, DashboardProviderService>();
            services.AddTransient <IDashboardPartDriveService, DashboardWelcomePartService>();
            services.AddTransient <IDashboardPartDriveService, DashboardEventLogPartService>();

            services.TryAddTransient <IDataArchivedService, DataArchivedService>();
            services.TryAddTransient <IExtendFieldService, ExtendFieldService>();
            services.TryAddTransient <INotifyService, NotifyService>();
            services.AddTransient <IUserCenterLinksProvider, UserCenterLinksProvider>();
            services.TryAddTransient <ILayoutService, LayoutService>();
            services.TryAddTransient <ILayoutHtmlService, LayoutHtmlService>();
            services.TryAddTransient <IMediaService, MediaService>();
            services.TryAddTransient <IPageService, PageService>();
            services.TryAddTransient <IApplicationSettingService, ApplicationSettingService>();
            services.TryAddTransient <IThemeService, ThemeService>();
            services.TryAddTransient <IWidgetTemplateService, WidgetTemplateService>();
            services.TryAddTransient <IWidgetBasePartService, WidgetBasePartService>();
            services.TryAddTransient <IZoneService, ZoneService>();
            services.TryAddTransient <Rule.IRuleService, Rule.RuleService>();

            services.AddScoped <IOnModelCreating, EntityFrameWorkModelCreating>();

            services.AddTransient <Easy.Notification.ISmtpProvider, SmtpProvider>();
            services.AddTransient <IPackageInstaller, ThemePackageInstaller>();
            services.AddTransient <IPackageInstaller, WidgetPackageInstaller>();
            services.AddTransient <IPackageInstaller, FilePackageInstaller>();
            services.AddTransient <IPackageInstaller, DataDictionaryPackageInstaller>();
            services.AddTransient <IPackageInstallerProvider, PackageInstallerProvider>();
            services.AddTransient <IEventViewerService, EventViewerService>();

            services.ConfigureCache <IEnumerable <WidgetBase> >();
            services.ConfigureCache <IEnumerable <ZoneEntity> >();
            services.ConfigureCache <IEnumerable <LayoutHtml> >();

            services.ConfigureMetaData <ArticleEntity, ArticleEntityMeta>();
            services.ConfigureMetaData <ArticleType, ArtycleTypeMetaData>();
            services.ConfigureMetaData <BreadcrumbWidget, BreadcrumbWidgetMetaData>();
            services.ConfigureMetaData <CarouselEntity, CarouselEntityMetaData>();
            services.ConfigureMetaData <CarouselWidget, CarouselWidgetMetaData>();
            services.ConfigureMetaData <CarouselItemEntity, CarouselItemEntityMeta>();
            services.ConfigureMetaData <HtmlWidget, HtmlWidgetMetaData>();
            services.ConfigureMetaData <ImageWidget, ImageWidgetMedaData>();
            services.ConfigureMetaData <NavigationEntity, NavigationEntityMeta>();
            services.ConfigureMetaData <NavigationWidget, NavigationWidgetMetaData>();
            services.ConfigureMetaData <ScriptWidget, ScriptWidgetMetaData>();
            services.ConfigureMetaData <StyleSheetWidget, StyleSheetWidgetMetaData>();
            services.ConfigureMetaData <VideoWidget, VideoWidgetMetaData>();
            services.ConfigureMetaData <DataArchived.DataArchived, DataArchivedMetaData>();
            services.ConfigureMetaData <ExtendFieldEntity, ExtendFieldEntityMetaData>();
            services.ConfigureMetaData <LayoutEntity, LayoutEntityMetaData>();
            services.ConfigureMetaData <MediaEntity, MediaEntityMetaData>();
            services.ConfigureMetaData <PageEntity, PageMetaData>();
            services.ConfigureMetaData <ProductEntity, ProductMetaData>();
            services.ConfigureMetaData <ProductCategory, ProductCategoryMetaData>();
            services.ConfigureMetaData <ProductImage, ProductImageMetaData>();
            services.ConfigureMetaData <ApplicationSetting, ApplicationSettingMedaData>();
            services.ConfigureMetaData <ThemeEntity, ThemeEntityMetaData>();
            services.ConfigureMetaData <ZoneEntity, ZoneEntityMetaData>();
            services.ConfigureMetaData <Rule.Rule, Rule.RuleMetaData>();
            services.ConfigureMetaData <Rule.RuleItem, Rule.RuleItemMetaData>();
            services.ConfigureMetaData <SmtpSetting, SmtpSettingMetaData>();
            services.ConfigureMetaData <Robots, RobotsMetaData>();

            services.Configure <NavigationWidget>(option =>
            {
                option.DataSourceLinkTitle = "导航";
                option.DataSourceLink      = "~/admin/Navigation";
            });

            services.Configure <CarouselWidget>(option =>
            {
                option.DataSourceLinkTitle = "焦点图";
                option.DataSourceLink      = "~/admin/Carousel";
            });
            #region 数据库配置
            services.AddSingleton <IDatabaseConfiguring, EntityFrameWorkConfigure>();
            services.AddSingleton <IDbConnectionPool, SimpleDbConnectionPool>();
            //池的配置:
            //MaximumRetained规定池的容量(常态最大保有数量)。
            //MaximumRetained为0时,相当于不使用DbConnection池,
            //但因为在Request期间Connection是保持打开的,所以对许多场合还是有性能改善的。
            services.AddSingleton(new DbConnectionPool.Options()
            {
                MaximumRetained = 128
            });
            //提供在Request期间租、还DbConnection的支持
            services.AddScoped <IConnectionHolder, TransientConnectionHolder>();
            services.AddDbContextOptions <CMSDbContext>();
            services.AddDbContext <CMSDbContext>();
            services.AddScoped <EasyDbContext>((provider) => provider.GetService <CMSDbContext>());
            DatabaseOption databaseOption = configuration.GetSection("Database").Get <DatabaseOption>();
            DataTableAttribute.IsLowerCaseTableNames = databaseOption.DbType == DbTypes.MySql;
            services.AddSingleton(databaseOption);
            #endregion

            services.UseEasyFrameWork(configuration);
            foreach (IPluginStartup item in services.LoadAvailablePlugins())
            {
                item.Setup(new object[] { services, mvcBuilder });
            }

            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetService)
            {
                services.TryAddTransient(item.Value);
            }
            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetModel)
            {
                services.TryAddTransient(item.Value);
            }

            services.Configure <AuthorizationOptions>(options =>
            {
                PermissionKeys.Configure(options);
                KnownRequirements.Configure(options);
            });

            services.AddAuthentication(DefaultAuthorizeAttribute.DefaultAuthenticationScheme)
            .AddCookie(DefaultAuthorizeAttribute.DefaultAuthenticationScheme, o =>
            {
                o.LoginPath        = new PathString("/Account/Login");
                o.AccessDeniedPath = new PathString("/Error/Forbidden");
            })
            .AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>
            {
                option.LoginPath = new PathString("/Account/Signin");
            });
        }
コード例 #4
0
 /// <summary>
 /// происходит в методе конфигурировании сервиса после срабатывания AddMvc
 /// </summary>
 public static void OnConfigureServicesAfterAddMvc(IServiceCollection services, IMvcBuilder mvcBuilder, IConfiguration configuration)
 {
     foreach (var eventse in _onStartupEvents)
     {
         eventse.OnConfigureServicesAfterAddMvc(services, mvcBuilder, configuration);
     }
 }
コード例 #5
0
        /// <summary>
        /// 添加规范化结果服务
        /// </summary>
        /// <param name="mvcBuilder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddUnifyResult(this IMvcBuilder mvcBuilder)
        {
            mvcBuilder.AddUnifyResult <RESTfulResultProvider>();

            return(mvcBuilder);
        }
コード例 #6
0
 public static IMvcBuilder AddJsonHalFormatterServices(this IMvcBuilder builder)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcJsonHalMediaSetup>());
     return(builder);
 }
コード例 #7
0
        public static IMvcBuilder AddGatewayApplicationParts(this IMvcBuilder builder)
        {
            builder.AddApplicationPart(typeof(BoundedContextController).Assembly);

            return(builder);
        }
コード例 #8
0
 /// <summary>
 /// Adds all required stuff in order for TOTP strong customer authentication (SCA) to work.
 /// </summary>
 /// <param name="builder">IdentityServer builder Interface.</param>
 /// <param name="configure">Configuration used in <see cref="Rfc6238AuthenticationService"/> service.</param>
 public static IMvcBuilder AddTotp(this IMvcBuilder builder, Action <TotpOptions> configure = null) => AddTotp <TotpService>(builder, configure);
コード例 #9
0
 /// <summary>
 /// 添加常用JSON类型转换
 /// </summary>
 /// <param name="builder"></param>
 /// <returns></returns>
 public static IMvcBuilder AddMangoJsonConvert(this IMvcBuilder builder)
 {
     return(builder);
 }
コード例 #10
0
 public override void ConfigureMvc(IMvcBuilder builder)
 {
 }
コード例 #11
0
 public static IMvcBuilder AddWebApiProxyServer(this IMvcBuilder mvcBuilder)
 {
     AppDomain.CurrentDomain.UpdateExcutingAssemblies();
     mvcBuilder.Services.AddMvcCore().AddWebApiProxyServer();
     return(mvcBuilder);
 }
コード例 #12
0
ファイル: PluginManager.cs プロジェクト: killvxk/btcpayserver
        public static IMvcBuilder AddPlugins(this IMvcBuilder mvcBuilder, IServiceCollection serviceCollection,
                                             IConfiguration config, ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger(typeof(PluginManager));
            var pluginsFolder = new DataDirectories().Configure(config).PluginDir;
            var plugins       = new List <IBTCPayServerPlugin>();

            serviceCollection.Configure <KestrelServerOptions>(options =>
            {
                options.Limits.MaxRequestBodySize = int.MaxValue; // if don't set default value is: 30 MB
            });
            _logger.LogInformation($"Loading plugins from {pluginsFolder}");
            Directory.CreateDirectory(pluginsFolder);
            ExecuteCommands(pluginsFolder);
            List <(PluginLoader, Assembly, IFileProvider)> loadedPlugins =
                new List <(PluginLoader, Assembly, IFileProvider)>();
            var systemExtensions = GetDefaultLoadedPluginAssemblies();

            plugins.AddRange(systemExtensions.SelectMany(assembly =>
                                                         GetAllPluginTypesFromAssembly(assembly).Select(GetPluginInstanceFromType)));
            foreach (IBTCPayServerPlugin btcPayServerExtension in plugins)
            {
                btcPayServerExtension.SystemPlugin = true;
            }

            var orderFilePath = Path.Combine(pluginsFolder, "order");

            var availableDirs = Directory.GetDirectories(pluginsFolder);
            var orderedDirs   = new List <string>();

            if (File.Exists(orderFilePath))
            {
                var order = File.ReadLines(orderFilePath);
                foreach (var s in order)
                {
                    if (availableDirs.Contains(s))
                    {
                        orderedDirs.Add(s);
                    }
                }

                orderedDirs.AddRange(availableDirs.Where(s => !orderedDirs.Contains(s)));
            }
            else
            {
                orderedDirs = availableDirs.ToList();
            }

            var disabledPlugins = GetDisabledPlugins(pluginsFolder);



            foreach (var dir in orderedDirs)
            {
                var pluginName     = Path.GetFileName(dir);
                var pluginFilePath = Path.Combine(dir, pluginName + ".dll");
                if (disabledPlugins.Contains(pluginName))
                {
                    continue;
                }
                if (!File.Exists(pluginFilePath))
                {
                    _logger.LogError(
                        $"Error when loading plugin {pluginName} - {pluginFilePath} does not exist");
                    continue;
                }

                var plugin = PluginLoader.CreateFromAssemblyFile(
                    pluginFilePath, // create a plugin from for the .dll file
                    config =>
                {
                    // this ensures that the version of MVC is shared between this app and the plugin
                    config.PreferSharedTypes = true;
                    config.IsUnloadable      = true;
                });

                mvcBuilder.AddPluginLoader(plugin);
                var pluginAssembly = plugin.LoadDefaultAssembly();
                _pluginAssemblies.Add(pluginAssembly);
                _plugins.Add(plugin);
                var fileProvider = CreateEmbeddedFileProviderForAssembly(pluginAssembly);
                loadedPlugins.Add((plugin, pluginAssembly, fileProvider));
                plugins.AddRange(GetAllPluginTypesFromAssembly(pluginAssembly)
                                 .Select(GetPluginInstanceFromType));
            }

            foreach (var plugin in plugins)
            {
                try
                {
                    _logger.LogInformation(
                        $"Adding and executing plugin {plugin.Identifier} - {plugin.Version}");
                    plugin.Execute(serviceCollection);
                    serviceCollection.AddSingleton(plugin);
                }
                catch (Exception e)
                {
                    _logger.LogError(
                        $"Error when loading plugin {plugin.Identifier} - {plugin.Version}{Environment.NewLine}{e.Message}");
                }
            }

            return(mvcBuilder);
        }
コード例 #13
0
        public virtual void LoadComponents(IServiceCollection services, IMvcBuilder builder)
        {
            var entityList = new List <Type>();
            var cacheItems = new List <HisarCacheAttribute>();

            var externalComponentsDirectory = Path.GetFullPath("ExternalComponents");

            if (!Directory.Exists(externalComponentsDirectory))
            {
                Directory.CreateDirectory(externalComponentsDirectory);
            }

            var externalComponentsRefDirectory = Path.Combine(externalComponentsDirectory, "refs");

            PathUtility.CopyToFiles(externalComponentsDirectory, externalComponentsRefDirectory);

            // Local packages loader
            var fileFullPaths = Directory.GetFiles(externalComponentsRefDirectory);

            if (fileFullPaths != null && fileFullPaths.Any())
            {
                foreach (var fileFullPath in fileFullPaths)
                {
                    var fileName = Path.GetFileName(fileFullPath);
                    if (fileName.StartsWith(ComponentConventionBaseNamespace, StringComparison.OrdinalIgnoreCase) &&
                        Path.GetExtension(fileName) == ".dll")
                    {
                        var fullPath = Path.GetFullPath(fileFullPath);

                        // AssemblyLoadContext.Default.Resolving += ReferencedAssembliesResolver.Resolving;
                        var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
                        ReferencedAssembliesResolver.ResolveAssemblies(GetResolveCallback(), externalComponentsRefDirectory, assembly);
                        RegisterComponent(services, builder, assembly, cacheItems);
                    }
                    else
                    {
                        var filename = Path.GetFileName(fileFullPath);
                        if (!filename.Contains("NetCoreStack.Hisar") && filename.EndsWith(".dll"))
                        {
                            var fullPath      = Path.GetFullPath(fileFullPath);
                            var entryAssembly = Assembly.GetEntryAssembly();

                            var assemblyName = Path.GetFileNameWithoutExtension(filename);
                            if (entryAssembly.GetReferencedAssemblies().Any(x => x.Name == assemblyName))
                            {
                                continue;
                            }

                            try
                            {
                                AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
                            }
                            catch (Exception ex)
                            {
                                var resolved = GetResolveCallback().TryLoad(AssemblyLoadContext.Default, entryAssembly, fullPath, ex);
                                if (!resolved)
                                {
                                    throw new FileLoadException($"{fullPath} could not be loaded! [Nuget Source]");
                                }
                            }
                        }
                    }
                }
            }

            var componentsJsonPath = PathUtility.TryGetComponentsJson(externalComponentsDirectory);

            if (!string.IsNullOrEmpty(componentsJsonPath))
            {
                LoadComponentsJson(services, builder, cacheItems, componentsJsonPath, externalComponentsRefDirectory);
            }

            services.AddSingleton <ICacheItemResolver>(new DefaultCacheItemResolver(cacheItems));

            services.AddImplementations <IUsernamePasswordValidator>(ComponentAssemblyLookup);
            services.AddImplementations <IUserRegistration>(ComponentAssemblyLookup);
        }
コード例 #14
0
ファイル: Dashboard.cs プロジェクト: imanys/Solen.Api
        public static IServiceCollection AddDashboard(this IServiceCollection services, IMvcBuilder mvcBuilder)
        {
            // Controllers
            mvcBuilder.AddApplicationPart(typeof(CoursesInfoController).GetTypeInfo().Assembly);

            //------------------------- Queries
            // GetCoursesInfo
            services.AddScoped <IGetCoursesInfoService, GetCoursesInfoService>();
            services.AddScoped <IGetCoursesInfoRepository, GetCoursesInfoRepository>();
            // GetLearningPathsInfo
            services.AddScoped <IGetLearningPathsInfoService, GetLearningPathsInfoService>();
            services.AddScoped <IGetLearningPathsInfoRepository, GetLearningPathsInfoRepository>();
            // GetStorageInfo
            services.AddScoped <IGetStorageInfoService, GetStorageInfoService>();
            // GetUserCountInfo
            services.AddScoped <IGetUserCountInfoService, GetUserCountInfoService>();
            // GetLearnerInfo
            services.AddScoped <IGetLearnerInfoService, GetLearnerInfoService>();
            services.AddScoped <IGetLearnerInfoRepository, GetLearnerInfoRepository>();


            return(services);
        }
コード例 #15
0
 /// <summary>
 /// Adds the fluent validation options to the MvcBuilder pipline.
 /// </summary>
 /// <param name="mvcBuilder"></param>
 /// <param name="configurationExpression"></param>
 /// <returns></returns>
 public static IMvcBuilder AddFluentValidation(this IMvcBuilder mvcBuilder, Action <FluentValidationModelValidatorProvider> configurationExpression = null)
 {
     return(AddFluentValidation(mvcBuilder, null, configurationExpression));
 }
 /// <summary>
 ///     Configue the <see cref="IMvcBuilder" /> to insert the <see cref="FlagsEnumModelBinder" />.
 /// </summary>
 /// <param name="builder">The <see cref="IMvcBuilder" /> object to be configuring.</param>
 /// <returns>The <paramref name="builder" /> object.</returns>
 public static IMvcBuilder AddFlagsEnumModelBinderProvider(this IMvcBuilder builder)
 {
     builder.AddMvcOptions(options => AddFlagsEnumModelBinderProvider(options));
     return(builder);
 }
コード例 #17
0
 public static IMvcBuilder AddProductModule(this IMvcBuilder builder)
 {
     return(builder.AddApplicationPart(Assembly.GetExecutingAssembly()));
 }
コード例 #18
0
 protected virtual void ConfigureFormatters(IMvcBuilder mvcBuilder)
 {
     mvcBuilder
     .WithJsonFormattersBasedOnJil(OptionsExtensions.Default)
     .WithProtobufFormatters();
 }
コード例 #19
0
 /// <summary>
 /// Adds all required stuff in order for TOTP strong customer authentication (SCA) to work.
 /// </summary>
 /// <typeparam name="TotpService">The type of <see cref="ITotpService"/> service implementation to use.</typeparam>
 /// <param name="builder">IdentityServer builder Interface.</param>
 /// <param name="configure">Configuration used in <see cref="Rfc6238AuthenticationService"/> service.</param>
 public static IMvcBuilder AddTotp <TotpService>(this IMvcBuilder builder, Action <TotpOptions> configure = null) where TotpService : class, ITotpService
 {
     builder.Services.AddDefaultTotpService(configure);
     builder.ConfigureApplicationPartManager(x => x.FeatureProviders.Add(new TotpFeatureProvider()));
     return(builder);
 }
コード例 #20
0
 public static IMvcBuilder AddNewtonsoftJsonWithStringEnumConverter(
     this IMvcBuilder mvcBuilder)
 {
     return(mvcBuilder.AddNewtonsoftJson(options =>
                                         options.SerializerSettings.Converters.Add(new StringEnumConverter())));
 }
コード例 #21
0
 public static IMvcBuilder AddControllerSpyControllerAssembly(this IMvcBuilder builder)
 {
     return(builder.AddApplicationPart(typeof(ControllerSpyExtensions).Assembly));
 }
コード例 #22
0
 public static void AddTeapot(this IMvcBuilder mvcBuilder)
 {
     mvcBuilder.AddApplicationPart(typeof(TeapotController).Assembly);
 }
コード例 #23
0
        public static IMvcBuilder AddApiExtensions(this IMvcBuilder builder, IConfigurationSection config = null, Action <ApiExtensionOptions> build = null, Type exception = null)
        {
            var apiOptions = new ApiExtensionOptions();

            #region Include services needed for building uri's in the paging object

            builder.Services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            #endregion

            #region Register Options

            if (config != null && build != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(x => { });
            }
            if (config != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(config);
                config.Bind(apiOptions);
            }
            if (build != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(build);
                build(apiOptions);
            }

            #endregion

            #region Configuration from options

            if (!apiOptions.DisableGlobalErrorHandling)
            {
                builder.AddMvcOptions(options =>
                {
                    options.Filters.Add(typeof(GlobalExceptionFilter));
                });
            }

            if (!apiOptions.DisableVersioning)
            {
                builder.AddMvcOptions(options =>
                {
                    options.Conventions.Insert(0, new RouteConvention(new RouteAttribute("{apiVersion}")));
                });
            }

            #endregion

            builder.AddMvcOptions(options =>
            {
                options.Filters.Add(new PagedResultAttribute()
                {
                    Order = 1000
                });
            });

            builder.AddJsonOptions(x =>
            {
                x.SerializerSettings.ContractResolver     = new BaseContractResolver();
                x.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                x.SerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
                x.SerializerSettings.Converters.Add(new TimeSpanConverter());
                x.SerializerSettings.Converters.Add(new GuidConverter());
                x.SerializerSettings.Formatting = Formatting.None;
            });

            return(builder);
        }
コード例 #24
0
        public static IMvcBuilder AddApiExtensions(this IMvcBuilder builder, IConfigurationSection config = null, Action <ApiExtensionOptions> build = null)
        {
            var apiOptions = new ApiExtensionOptions();

            #region Include services needed for building uri's in the paging object

            builder.Services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            builder.Services.AddScoped <IUrlHelper>(x =>
            {
                var actionContext = x.GetService <IActionContextAccessor>().ActionContext;
                return(new UrlHelper(actionContext));
            });

            builder.Services.AddScoped <ILinkProvider, LinkProvider>();
            #endregion

            #region Register Options

            if (config != null && build != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(x => { });
            }
            if (config != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(config);

                config.Bind(apiOptions);
            }
            if (build != null)
            {
                builder.Services.Configure <ApiExtensionOptions>(build);
                build(apiOptions);
            }

            #endregion

            #region Configuration from options

            if (!apiOptions.DisableGlobalErrorHandling && !apiOptions.DisableGlobalExceptionFilter)
            {
                builder.AddMvcOptions(options =>
                {
                    options.Filters.Add(typeof(GlobalExceptionFilter));
                });
            }

            if (!apiOptions.DisableVersioning)
            {
                builder.AddMvcOptions(options =>
                {
                    options.Conventions.Insert(0, new RouteConvention(new RouteAttribute("{apiVersion}")));
                });
            }

            #endregion

            builder.AddMvcOptions(options =>
            {
                options.Filters.Insert(0, new ConsumesAttribute("application/json"));
                options.Filters.Insert(1, new ProducesAttribute("application/json"));

                options.ModelBinderProviders.Insert(0, new CommaDelimitedArrayModelBinderProvider());

                JsonOutputFormatter jsonFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault();

                jsonFormatter?.SupportedMediaTypes.Add("application/hal+json");
            });

            builder.AddJsonOptions(x =>
            {
                x.SerializerSettings.ContractResolver     = new BaseContractResolver();
                x.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                x.SerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
                x.SerializerSettings.Converters.Add(new TimeSpanConverter());
                x.SerializerSettings.Converters.Add(new PagedResultConverter());
                x.SerializerSettings.Converters.Add(new GuidConverter());
                x.SerializerSettings.Formatting = Formatting.None;
            });

            return(builder);
        }
コード例 #25
0
        private static void LoaderAssembly(FileInfo pathConfig, IEnumerable <XElement> moduleLoaders, IMvcBuilder mvcBuilder = null)
        {
            foreach (var module in moduleLoaders)
            {
                var moduleName = module.Attribute("name")?.Value;
                var modulePath = module.Attribute("path")?.Value;
                try
                {
                    Console.WriteLine(pathConfig.FullName);
                    var isMvcLoad = Convert.ToBoolean(module.Attribute("isMvc")?.Value ?? "false");
                    //if (isMvcLoad && mvcBuilder == null)
                    //    continue;
                    //if (!isMvcLoad && mvcBuilder != null)
                    //    continue;
                    if (string.IsNullOrEmpty(modulePath))
                    {
                        Console.WriteLine($"Пустой путь при загрузке библиотеки модуля {moduleName}");
                        continue;
                    }

                    FileInfo file = new FileInfo(Path.Combine(pathConfig.DirectoryName, modulePath));
                    var      ass  = AssemblyLoadContext.Default
                                    .LoadFromAssemblyPath(file.FullName);

                    if (isMvcLoad)
                    {
                        mvcBuilder?.AddApplicationPart(ass);
                    }
                    Core.LoaderModules.LoaderExtensions.XmlDocs =
                        Core.LoaderModules.LoaderExtensions.XmlDocs ?? new List <string>();
                    if (file.Exists)
                    {
                        var fileXml = new FileInfo(Path.Combine(pathConfig.DirectoryName, modulePath.Replace(".dll", ".xml").Replace(".DLL", ".xml")));
                        if (fileXml.Exists)
                        {
                            Core.LoaderModules.LoaderExtensions.XmlDocs.Add(fileXml.FullName);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Не удалось загрузить библиотеку {moduleName}");
                    Console.WriteLine(e);
                }
            }
        }
コード例 #26
0
 public static IMvcBuilder AddCsvFormatter(this IMvcBuilder mvcBuilder) =>
 mvcBuilder.AddMvcOptions(options =>
 {
     options.InputFormatters.Add(new CsvInputFormatter());
     options.OutputFormatters.Add(new CsvOutputFormatter());
 });
コード例 #27
0
 public static IMvcBuilder AddCustomCsvFormatter(this IMvcBuilder builder) =>
 builder.AddMvcOptions(
     config => config.OutputFormatters.Add(new CsvOutputFormatter())
     );
コード例 #28
0
 /// <summary>
 /// Adds version negotiation using <see cref="AcceptHeaderParameterVersionStrategy"/>.
 /// </summary>
 public static IMvcBuilder AddVersionNegotiation(this IMvcBuilder builder)
 {
     return(builder.AddVersionNegotiation(options => { }));
 }
コード例 #29
0
 /// <summary>
 /// Adds an action filter required to safely throw <see cref="HttpException" /> in action methods.
 /// </summary>
 /// <param name="builder">The ASP.NET MVC builder.</param>
 public static IMvcBuilder AddHttpErrors(this IMvcBuilder builder)
 => builder.AddMvcOptions(o => o.Filters.Add(new HttpExceptionActionFilter()));
コード例 #30
0
        public static IMvcBuilder AddActionAndModelStateValidationAndBadRequestLogging(this IMvcBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Services.Configure <MvcOptions>(opt =>
            {
                opt.Filters.Add <ActionLoggingFilter>();
                opt.Filters.Add <ModelStateValidationLoggingFilter>();
                opt.Filters.Add <BadRequestLoggingFilter>();
            });

            builder.Services.AddTransient <ActionLoggingFilter>();
            builder.Services.AddTransient <ModelStateValidationLoggingFilter>();
            builder.Services.AddTransient <BadRequestLoggingFilter>();

            return(builder);
        }
コード例 #31
0
 public virtual IMvcBuilder MvcChain(IMvcBuilder source)
 {
     return(source);
 }
コード例 #32
0
        /// <summary>
        /// Extension method for adding the jellyfin API to the service collection.
        /// </summary>
        /// <param name="serviceCollection">The service collection.</param>
        /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
        /// <param name="config">The <see cref="NetworkConfiguration"/>.</param>
        /// <returns>The MVC builder.</returns>
        public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable <Assembly> pluginAssemblies, NetworkConfiguration config)
        {
            IMvcBuilder mvcBuilder = serviceCollection
                                     .AddCors()
                                     .AddTransient <ICorsPolicyProvider, CorsPolicyProvider>()
                                     .Configure <ForwardedHeadersOptions>(options =>
            {
                // https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
                // Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues.

                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                if (config.KnownProxies.Length == 0)
                {
                    options.KnownNetworks.Clear();
                    options.KnownProxies.Clear();
                }
                else
                {
                    AddProxyAddresses(config, config.KnownProxies, options);
                }

                // Only set forward limit if we have some known proxies or some known networks.
                if (options.KnownProxies.Count != 0 || options.KnownNetworks.Count != 0)
                {
                    options.ForwardLimit = null;
                }
            })
                                     .AddMvc(opts =>
            {
                // Allow requester to change between camelCase and PascalCase
                opts.RespectBrowserAcceptHeader = true;

                opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
                opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());

                opts.OutputFormatters.Add(new CssOutputFormatter());
                opts.OutputFormatters.Add(new XmlOutputFormatter());

                opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider());
            })

                                     // Clear app parts to avoid other assemblies being picked up
                                     .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
                                     .AddApplicationPart(typeof(StartupController).Assembly)
                                     .AddJsonOptions(options =>
            {
                // Update all properties that are set in JsonDefaults
                var jsonOptions = JsonDefaults.PascalCaseOptions;

                // From JsonDefaults
                options.JsonSerializerOptions.ReadCommentHandling    = jsonOptions.ReadCommentHandling;
                options.JsonSerializerOptions.WriteIndented          = jsonOptions.WriteIndented;
                options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
                options.JsonSerializerOptions.NumberHandling         = jsonOptions.NumberHandling;

                options.JsonSerializerOptions.Converters.Clear();
                foreach (var converter in jsonOptions.Converters)
                {
                    options.JsonSerializerOptions.Converters.Add(converter);
                }

                // From JsonDefaults.PascalCase
                options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
            });

            foreach (Assembly pluginAssembly in pluginAssemblies)
            {
                mvcBuilder.AddApplicationPart(pluginAssembly);
            }

            return(mvcBuilder.AddControllersAsServices());
        }