Esempio n. 1
0
        /// <summary>
        /// 自动注册所有 Area
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="env"></param>
        /// <param name="eachRegsiterAction">遍历到每一个 Register 额外的操作</param>
        /// <returns></returns>
        public static IMvcBuilder AddNcfAreas(this IMvcBuilder builder, Microsoft.Extensions.Hosting.IHostEnvironment /*IWebHostEnvironment*/ env, Action <IAreaRegister> eachRegsiterAction = null)
        {
            AssembleScanHelper.AddAssembleScanItem(assembly =>
            {
                try
                {
                    var areaRegisterTypes = assembly.GetTypes()
                                            .Where(z => z.GetInterface(nameof(IAreaRegister)) != null)
                                            .ToArray();

                    foreach (var registerType in areaRegisterTypes)
                    {
                        var register = Activator.CreateInstance(registerType, true) as IAreaRegister;
                        if (register != null)
                        {
                            register.AuthorizeConfig(builder, env); //进行注册
                            eachRegsiterAction?.Invoke(register);   //执行额外的操作
                        }
                        else
                        {
                            SenparcTrace.BaseExceptionLog(new BaseException($"{registerType.Name} 类型没有实现接口 IAreaRegister!"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    SenparcTrace.SendCustomLog("AddNcfAreas() 自动扫描程序集报告(非程序异常):" + assembly.FullName, ex.ToString());
                }
            }, false);
            return(builder);
        }
Esempio n. 2
0
        /// <summary>
        /// 扫描自动依赖注入的接口
        /// </summary>
        public static IServiceCollection ScanAssamblesForAutoDI(this IServiceCollection services)
        {
            //遍历所有程序集进行注册
            AssembleScanHelper.AddAssembleScanItem(assembly =>
            {
                var areaRegisterTypes = assembly.GetTypes() //.GetExportedTypes()
                                        .Where(z => !z.IsAbstract && !z.IsInterface && z.GetInterface(nameof(IAutoDI)) != null)
                                        .ToArray();

                DILifecycleType dILifecycleType = DILifecycleType.Scoped;

                foreach (var registerType in areaRegisterTypes)
                {
                    try
                    {
                        //判断特性标签
                        var attrs = System.Attribute.GetCustomAttributes(registerType, false).Where(z => z is AutoDITypeAttribute);
                        if (attrs.Count() > 0)
                        {
                            var attr        = attrs.First() as AutoDITypeAttribute;
                            dILifecycleType = attr.DILifecycleType;//使用指定的方式
                        }

                        //针对不同的类型进行不同生命周期的 DI 设置
                        switch (dILifecycleType)
                        {
                        case DILifecycleType.Scoped:
                            services.AddScoped(registerType);
                            break;

                        case DILifecycleType.Singleton:
                            services.AddSingleton(registerType);
                            break;

                        case DILifecycleType.Transient:
                            services.AddTransient(registerType);
                            break;

                        default:
                            throw new NotImplementedException($"未处理此 DILifecycleType 类型:{dILifecycleType.ToString()}");
                        }
                    }
                    catch (Exception ex)
                    {
                        SenparcTrace.BaseExceptionLog(ex);
                    }
                }
            }, false);

            return(services);
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //提供网站根目录
            if (Env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = Env.ContentRootPath;
                SiteConfig.WebRootPath     = Env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSenparcGlobalServices(Configuration);

            services.AddRazorPages();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(Configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(Configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            services.AddHttpContextAccessor();
            //激活 Xncf 扩展引擎(必须)
            services.StartEngine(Configuration);
            //指定数据库类型(可选),默认为 SQLiteMemoryDatabaseConfiguration
            services.AddDatabase <SQLServerDatabaseConfiguration>();
            //services.UseDatabase<SqliteMemoryDatabaseConfiguration>();
        }
        /// <summary>
        /// 注册 IServiceCollection 和 MemoryCache
        /// </summary>
        public void RegisterServiceCollection()
        {
            var serviceCollection = new ServiceCollection();
            var configBuilder     = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appsettings.json", false, false);
            var config = configBuilder.Build();

            Configuration = config;

            _senparcSetting = new SenparcSetting()
            {
                IsDebug = true
            };
            config.GetSection("SenparcSetting").Bind(_senparcSetting);

            serviceCollection.AddDatabase <SqliteMemoryDatabaseConfiguration>();//使用 SQLServer数据库


            SiteConfig.WebRootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");

            Senparc.Ncf.Core.Register.TryRegisterMiniCore(services => { });
            serviceCollection.AddSenparcGlobalServices(config);

            serviceCollection.AddMemoryCache();//使用内存缓存
            serviceCollection.AddRouting();
            var builder = serviceCollection.AddRazorPages();

            builder.AddNcfAreas(_env.Object);

            //自动依赖注入扫描
            serviceCollection.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();


            var result     = serviceCollection.StartEngine(Configuration);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            ServiceProvider = serviceCollection.BuildServiceProvider();
        }
        /// <summary>
        /// 自动注册所有 Area
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IMvcBuilder AddNcfAreas(this IMvcBuilder builder, IWebHostEnvironment env)
        {
            AssembleScanHelper.AddAssembleScanItem(assembly =>
            {
                try
                {
                    var areaRegisterTypes = assembly.GetTypes()
                                            .Where(z => z.GetInterface(nameof(IAreaRegister)) != null)
                                            .ToArray();

                    foreach (var registerType in areaRegisterTypes)
                    {
                        var register = Activator.CreateInstance(registerType, true) as IAreaRegister;
                        register.AuthorizeConfig(builder, env);//进行注册
                    }
                }
                catch (Exception ex)
                {
                    SenparcTrace.SendCustomLog("AddNcfAreas() 自动扫描程序集报告(非程序异常):" + assembly.FullName, ex.ToString());
                }
            }, false);
            return(builder);
        }
Esempio n. 6
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});


            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})


            var builder = services.AddRazorPages()
                          .AddScfAreas()//注册所有 Scf 的 Area 模块(必须)
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

            ;


#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    var libraryPath = Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "Senparc.Areas.Admin"));
                    options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                });
            }
#endif


            //services.AddSenparcGlobalServices(configuration);//Senparc.CO2NET 全局注册    //已经在startup.cs中注册

            //支持 AutoMapper
            services.AddAutoMapper(_ => _.AddProfile <Core.AutoMapProfile.AutoMapperConfigs>());

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"))
            .AddSenparcEntitiesDI();     //SQL Server设置

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();
            services.AddScoped(typeof(Areas.Admin.Filters.AuthenticationResultFilterAttribute));
            services.AddScoped(typeof(Areas.Admin.Filters.AuthenticationAsyncPageFilterAttribute));
            services.AddScoped(typeof(ISqlClientFinanceData), typeof(SqlClientFinanceData));
            services.AddScoped(typeof(ISqlBaseFinanceData), typeof(SqlClientFinanceData));
            services.AddScoped(typeof(Senparc.Scf.Repository.IRepositoryBase <>), typeof(Senparc.Scf.Repository.RepositoryBase <>));
            services.AddScoped(typeof(ISysButtonRespository), typeof(SysButtonRespository));
            services.AddScoped(typeof(Core.WorkContext.Provider.IAdminWorkContextProvider), typeof(Core.WorkContext.Provider.AdminWorkContextProvider));
            services.AddTransient <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, Microsoft.AspNetCore.Mvc.Infrastructure.ActionContextAccessor>();

            //激活 Xscf 扩展引擎
            services.StartEngine();
        }
Esempio n. 7
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});

            //启用以下代码强制使用 https 访问
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            //    options.HttpsPort = 443;
            //});

            //读取Log配置文件
            var repository = LogManager.CreateRepository("NETCoreRepository");

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = env.ContentRootPath;
                SiteConfig.WebRootPath     = env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})

            services.AddSenparcGlobalServices(configuration);

            var builder = services.AddRazorPages(opt =>
            {
                //opt.RootDirectory = "/";
            })
                          .AddScfAreas(env)//注册所有 Scf 的 Area 模块(必须)
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

            ;

#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    //自动索引所有需要使用 RazorRuntimeCompilation 的模块
                    foreach (var razorRegister in Senparc.Scf.XscfBase.Register.RegisterList.Where(z => z is IXscfRazorRuntimeCompilation))
                    {
                        try
                        {
                            var libraryPath = ((IXscfRazorRuntimeCompilation)razorRegister).LibraryPath;
                            options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                        }
                        catch (Exception ex)
                        {
                            SenparcTrace.BaseExceptionLog(ex);
                        }
                    }
                });
            }
#endif

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();

            //Repository & Service
            services.AddScoped(typeof(ISysButtonRespository), typeof(SysButtonRespository));

            //Other
            services.AddScoped(typeof(Scf.Core.WorkContext.Provider.IAdminWorkContextProvider), typeof(Scf.Core.WorkContext.Provider.AdminWorkContextProvider));
            services.AddTransient <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, Microsoft.AspNetCore.Mvc.Infrastructure.ActionContextAccessor>();

            //激活 Xscf 扩展引擎(必须)
            services.StartEngine(configuration);
        }
Esempio n. 8
0
        public static void AddNcfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});

            //启用以下代码强制使用 https 访问
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            //    options.HttpsPort = 443;
            //});

            //读取Log配置文件
            var repository = LogManager.CreateRepository("NETCoreRepository");

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = env.ContentRootPath;
                SiteConfig.WebRootPath     = env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})


            services.AddMultiTenant();                                        //注册多租户(按需)
            EntitySetKeys.TryLoadSetInfo(typeof(SenparcEntitiesMultiTenant)); //注册多租户数据库的对象(按需)
            services.AddScoped <ITenantInfoDbData, TenantInfoDbData>();
            services.AddScoped <TenantInfoRepository>();
            services.AddScoped <IClientRepositoryBase <TenantInfo>, TenantInfoRepository>();

            services.AddSenparcGlobalServices(configuration);//注册 CO2NET 基础引擎所需服务

            var builder = services.AddRazorPages(opt =>
            {
                //opt.RootDirectory = "/";
            })
                          .AddNcfAreas(env)//注册所有 Ncf 的 Area 模块(必须)
                          .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var values = actionContext.ModelState.Where(_ => _.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid).Select(_ => new { _.Key, Errors = _.Value.Errors.Select(__ => __.ErrorMessage) });
                    AjaxReturnModel commonReturnModel = new AjaxReturnModel <object>(values);
                    commonReturnModel.Success         = false;
                    commonReturnModel.Msg             = "参数校验未通过";
                    //commonReturnModel.StatusCode = Core.App.CommonReturnStatusCode.参数校验不通过;
                    return(new BadRequestObjectResult(commonReturnModel));
                };
            })
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    //自动索引所有需要使用 RazorRuntimeCompilation 的模块
                    foreach (var razorRegister in XncfRegisterManager.RegisterList.Where(z => z is IXncfRazorRuntimeCompilation))
                    {
                        try
                        {
                            var libraryPath = ((IXncfRazorRuntimeCompilation)razorRegister).LibraryPath;
                            options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                        }
                        catch (Exception ex)
                        {
                            SenparcTrace.BaseExceptionLog(ex);
                        }
                    }
                });
            }
#endif

            //TODO:在模块中注册
            services.AddScoped <Ncf.AreaBase.Admin.Filters.AuthenticationResultFilterAttribute>();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            ////添加多租户
            //services.AddMultiTenant();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();

            //Repository & Service
            services.AddScoped <ISysButtonRespository, SysButtonRespository>();

            //Other
            services.AddScoped <IAdminWorkContextProvider, AdminWorkContextProvider>();
            services.AddTransient <IActionContextAccessor, ActionContextAccessor>();

            //忽略某些 API
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_Work.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_MiniProgram.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_Open.ToString());
            //Senparc.CO2NET.WebApi.Register.OmitCategoryList.Add(Senparc.NeuChar.PlatformType.WeChat_OfficialAccount.ToString());

            //激活 Xncf 扩展引擎(必须)
            services.StartEngine(configuration);
        }
Esempio n. 9
0
        public static void AddScfServices(this IServiceCollection services, IConfiguration configuration, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});


            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc(options =>
            {
                //options.Filters.Add<HttpGlobalExceptionFilter>();
            })
            .SetCompatibilityVersion(compatibilityVersion)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;//支持 Area
                //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            })
            .AddScfAreas()//注册所有 Scf 的 Area 模块(必须)
            .AddXmlSerializerFormatters()
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
            //.AddSessionStateTempDataProvider()
            //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
            ;

            //services.AddSenparcGlobalServices(configuration);//Senparc.CO2NET 全局注册    //已经在startup.cs中注册

            //支持 AutoMapper
            services.AddAutoMapper();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"))
            .AddSenparcEntitiesDI();     //SQL Server设置


            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();


            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();


            services.AddScoped(typeof(ISqlClientFinanceData), typeof(SqlClientFinanceData));
        }