Beispiel #1
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddAuthentication(options =>
     {
         options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     }).AddCookie();
     services
     .AddOptions()
     .Configure <AppSettings>(Configuration)
     .Configure <ConnectionStrings>(Configuration.GetSection("ConnectionStrings"))
     .AddDbContext <IntelligentMonitorContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")))
     .AddSwaggerGen(s =>
     {
         s.SwaggerDoc("IntelligentMonitor", null);
         s.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "IntelligentMonitor.xml"));
     })
     .AddRouting(routes =>
     {
         routes.LowercaseUrls       = true;
         routes.AppendTrailingSlash = false;
     })
     .AddSingleton(HtmlEncoder.Create(UnicodeRanges.All))
     .AddSingleton <AppSettings>()
     .AddTransient <IAuthorizationHandler, PermissionAuthorizationHandler>()
     .AddTransient <UserProvider>()
     .AddMvc()
     .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
            AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Events.OnRedirectToLogin = ctx =>
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.FromResult(0));
                };
            });

            string permissionClaimName = nameof(Permission);

            services.AddAuthorization(options =>
            {
                foreach (string perm in Enum.GetNames(typeof(Permission)))
                {
                    options.AddPolicy(perm, policy => policy.RequireAssertion(context =>
                    {
                        var permClaim = context.User.Claims.FirstOrDefault(c => c.Type == permissionClaimName);
                        return(permClaim != null && permClaim.Value.Contains(perm));
                    }));
                }
                options.AddPolicy("Admin", policy => policy.RequireClaim("IsAdmin"));
            });

            var mvcBuilder = services.AddControllersWithViews();

            mvcBuilder.AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.Converters.Add(new DictionaryIntConverter());
            });

            services.AddRazorPages();
            services.AddHttpContextAccessor();

            services.AddSingleton <HtmlEncoder>(HtmlEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Arabic));

            var settings = Configuration.GetSection("Settings").Get <Settings>();

            services.AddSingleton(settings);

            string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), StringNormalizer.JSON_FILE_NAME);

            services.AddSingleton <IStringNormalizer>(new StringNormalizer(filePath));

            // configure db:
            var defaultConnection = Configuration.GetSection("DefaultConnection").Get <MongoConnectionSettings>();
            var customConnections = Configuration.GetSection("CustomConnections").Get <MongoConnectionSettings[]>();

            services.FindModelsAndAddMongoCollections(new Assembly[] { Assembly.GetAssembly(typeof(ClientAuthUser)), Assembly.GetAssembly(typeof(AuthUserX)) },
                                                      defaultConnection, customConnections);

            services.Configure <IISServerOptions>(options =>
            {
                options.AutomaticAuthentication = false;
            });
        }
Beispiel #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(o => o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()))
            .AddFeatureFolders()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            // Create the HttpClientFactory to provide the HttpClient to the Typed Client classes.
            services.AddHttpClient();

            // Display Cyrillic characters in HTML without encoding.
            services.AddSingleton(HtmlEncoder
                                  .Create(allowedRanges: new[] { UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic }));

            services.AddDbContext <AppIdentityDbContext>(o =>
                                                         o.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>(o => {
                o.Password.RequiredLength = 8;
                o.User.RequireUniqueEmail = true;
            })
            .AddPasswordValidator <CustomPasswordValidator>()
            .AddEntityFrameworkStores <AppIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddAutoMapper();
        }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            if (WebHostEnvironment.IsDevelopment())
            {
                services.AddRazorPages().AddRazorRuntimeCompilation();
            }
            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.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            services.AddControllersWithViews(options =>
            {
                options.Filters.Add <GlobalExceptionFilter>();
                options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider());
            }).AddNewtonsoftJson(options =>
            {
                // 返回数据首字母不小写,CamelCasePropertyNamesContractResolver是小写
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddMemoryCache();
            services.AddSession();
            services.AddHttpContextAccessor();

            services.AddOptions();

            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection"));
            GlobalContext.SystemConfig  = Configuration.GetSection("SystemConfig").Get <SystemConfig>();
            GlobalContext.Services      = services;
            GlobalContext.Configuration = Configuration;
        }
Beispiel #5
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers(options =>
     {
         options.Filters.Add <GlobalExceptionFilterAttribute>();  // 全局异常过滤器
         options.Filters.Add <GenericResultFilterAttribute>();    // 通用执行结果包装处理过滤器
                                                                  //options.Filters.Add<DefaultAuthorizeFilterAttribute>();    // 全局授权认证失败自定义结果过滤器
         //options.UseCentralRoutePrefix(new RouteAttribute("demoapi"));  //全局 添加路由控制前缀
     }).AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
         //options.JsonSerializerOptions.PropertyNamingPolicy = null;  // 可用于实现 首字母大小写的
         options.JsonSerializerOptions.WriteIndented = false;
     })
     .ConfigureApiBehaviorOptions(options =>
     {
         options.SuppressModelStateInvalidFilter = true; // 禁止默认模型验证结果处理
     })
     .AddFluentValidation(config =>                      // 请求模型参数验证
     {
         //config.ValidatorFactory = new FluentValidatorFactory();
         config.RunDefaultMvcValidationAfterFluentValidationExecutes = true; // false : 禁止默认模型验证
         config.ValidatorOptions.CascadeMode = CascadeMode.Stop;             // 不级联验证,第一个规则错误就停止
         //config.RegisterValidatorsFromAssemblyContaining<DepartmentCreateOrUpdateValidator>();
     });
     services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All)); // 解决中文乱码
     services.AddHostedService <NLogHostService>();                // NLog 关闭服务
     services.AddCalamus(Configuration, Environment);
 }
Beispiel #6
0
        public Card EncodeCardContentForReadonlyView(Card card)
        {
            List <string> linksInCardContent;
            List <string> boldWordsInCardContent;

            var htmle = HtmlEncoder.Create();


            linksInCardContent     = findCustomLinks(card.Front);
            boldWordsInCardContent = findCustomBoldWords(card.Front);
            card.Front             = htmle.Encode(card.Front);
            card.Front             = card.Front.Replace(htmle.Encode("<code>"), "<pre class='prettyprint lang-cs'>");
            card.Front             = card.Front.Replace(htmle.Encode("</code>"), "</pre>");

            card.Front = ReplaceCustomMarkupWithHTMLMarkup(card.Front, linksInCardContent, htmle, CardColors.crimson, AlterCustomLinksToHyperlinks);
            card.Front = ReplaceCustomMarkupWithHTMLMarkup(card.Front, boldWordsInCardContent, htmle, CardColors.crimson, AlterCustomBoldWordsToBoldTags);


            linksInCardContent     = findCustomLinks(card.Back);
            boldWordsInCardContent = findCustomBoldWords(card.Back);
            card.Back = htmle.Encode(card.Back);
            card.Back = card.Back.Replace(htmle.Encode("<code>"), "<pre class='prettyprint lang-cs'>");
            card.Back = card.Back.Replace(htmle.Encode("</code>"), "</pre>");

            card.Back = ReplaceCustomMarkupWithHTMLMarkup(card.Back, linksInCardContent, htmle, CardColors.royalblue, AlterCustomLinksToHyperlinks);
            card.Back = ReplaceCustomMarkupWithHTMLMarkup(card.Back, boldWordsInCardContent, htmle, CardColors.royalblue, AlterCustomBoldWordsToBoldTags);

            card = RestoreNewLine(card);
            return(card);
        }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Core();

            services.AddCors(options =>
            {
                options.AddPolicy("PolicyOrigin",
                                  builder => builder.WithOrigins("*")
                                  .WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                                  .AllowAnyHeader()
                                  );
            });

            services.Configure <GzipCompressionProviderOptions>(options =>
                                                                options.Level = CompressionLevel.Optimal
                                                                );
            services.AddResponseCompression();
            services.AddResponseCaching(options =>
            {
                options.UseCaseSensitivePaths = true;
                options.MaximumBodySize       = 1024;
            });

            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(
                    allowedRanges: new[] {
                UnicodeRanges.BasicLatin,
                UnicodeRanges.CjkUnifiedIdeographs
            }
                    )
                );

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Beispiel #8
0
        /// <summary>
        /// 配置多语言服务,
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddAppLocalization(this IMvcBuilder builder)
        {
            // 获取多语言配置选项
            using var serviceProvider = builder.Services.BuildServiceProvider();
            var localizationOptions = serviceProvider.GetService <IOptions <LocalizationSettingOptions> >().Value;

            // 注册请求多语言配置选项
            builder.Services.Configure((Action <RequestLocalizationOptions>)(options =>
            {
                // 如果设置了默认语言,则取默认语言,否则取第一个
                options.SetDefaultCulture(string.IsNullOrWhiteSpace(localizationOptions.DefaultCulture) ? localizationOptions.SupportedCultures[0] : localizationOptions.DefaultCulture)
                .AddSupportedCultures(localizationOptions.SupportedCultures)
                .AddSupportedUICultures(localizationOptions.SupportedCultures);

                // 自动根据客户端浏览器的语言实现多语言机制
                options.ApplyCurrentCultureToResponseHeaders = true;
            }));

            // 处理多语言在 Razor 视图中文乱码问题
            builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            // 配置视图多语言和验证多语言
            builder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                                                          factory.Create(I18n.LangType);
            });

            I18n.OnGetSelectCulturing = () =>
            {
                var httpContext = WebApp.HttpContext;
                if (httpContext == null)
                {
                    return(default);
Beispiel #9
0
        /// <summary>
        /// Outputs html content as string.
        /// </summary>
        public static string AsString(this IHtmlContent content)
        {
            var writer = new System.IO.StringWriter();

            content.WriteTo(writer, HtmlEncoder.Create());
            return(writer.ToString());
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <GzipCompressionProviderOptions>
                (options => options.Level = CompressionLevel.Fastest);
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
            });
            services.AddMvc(options => options.EnableEndpointRouting = false)
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson();

            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] {
                UnicodeRanges.BasicLatin,
                UnicodeRanges.CjkSymbolsandPunctuation,
                UnicodeRanges.Hiragana,
                UnicodeRanges.Katakana,
                UnicodeRanges.CjkUnifiedIdeographs
            })
                );
            services.AddControllers();
            services.AddRazorPages();

            var githubClientId     = Configuration.GetValue <string>("GITHUB_CLIENT_ID");
            var githubClientSecret = Configuration.GetValue <string>("GITHUB_CLIENT_SECRET");
            var githubOAuth        = new GithubOAuth(githubClientId, githubClientSecret);

            services.AddSingleton <GithubOAuth>(githubOAuth);
        }
Beispiel #11
0
        public static void RegisterServices(IServiceCollection services)
        {
            var assembly = AppDomain.CurrentDomain.Load("Emprise.MudServer");

            services.AddMediatR(assembly);

            services.AddHttpClient();



            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSignalR(x => {
                x.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
            });

            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddAutoMapper();

            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));

            services.AddScoped(typeof(IBaseDomainService <>), typeof(BaseDomainService <>));

            services.AddRouting(options => options.LowercaseUrls = true);

            services.AddScoped <INotificationHandler <DomainNotification>, DomainNotificationHandler>();
        }
Beispiel #12
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //初始化数据库
            services.AddDbContext <DataContext>(options => options.UseMySql(Configuration.GetConnectionString("MySql"),
                                                                            b => { b.MigrationsAssembly("ProgrammersLiveShow"); }));

            //注册路由
            services.AddMvc();

            //注册定时任务
            services.AddTimedJob();

            //注册Session
            services.AddSession(c => { c.IdleTimeout = TimeSpan.FromMinutes(30); });

            //注入读取配置文件
            services.AddOptions();
            services.Configure <ApplicationConfig>(Configuration.GetSection("ApplicationConfig"));
            services.Configure <SendMailConfig>(Configuration.GetSection("SendMailConfig"));

            //注册微信app信息
            WeixinConfig.RegistWeixinAppMsg();

            //解决界面显示HTML编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            //注册AutoFac
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterModule <RegestAutoFac>();
            containerBuilder.Populate(services);
            return(containerBuilder.Build().Resolve <IServiceProvider>());
        }
        public async Task <IActionResult> Comment(CommentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Post), new { slug = model.PostId }));
            }

            var user = await _userManager.GetUserAsync(User);

            var post = _repository.GetPostBySlug(model.PostId);
            //Sanitizing User Input
            //Because someone might try to inject a script
            //That may execute on the client
            //And that would be very bad
            var encodedComment = HtmlEncoder.Create().Encode(model.Message);

            post.Comments = post.Comments ?? new List <Comment>();
            post.Comments.Add(new Comment
            {
                Id         = Guid.NewGuid().ToString().Replace("-", string.Empty).ToLowerInvariant(),
                Message    = encodedComment,
                DatePosted = DateTime.Now,
                Username   = user.UserName,
                Gravator   = user.ImageUrl
            });
            _repository.UpdatePost(post);
            await _repository.SaveChangesAsync();

            return(RedirectToAction(nameof(Post), new { slug = post.Slug }));
        }
Beispiel #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // 后台登录授权验证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.LoginPath  = "/admin/account/login";
                options.LogoutPath = "/admin/account/logout";
                options.Cookie     = new CookieBuilder {
                    HttpOnly = true
                };
            });

            // 解决中文乱码
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            //DB
            var connection = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <BlogDBContext>(options => options.UseSqlServer(connection));
            //DI
            services.AddTransient <IArticleService, ArticleService>();
            services.AddTransient <IAccountService, AccountService>();
            services.AddTransient <ICategoryService, CategoryService>();
        }
Beispiel #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            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.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.AddMvc(options =>
            {
                options.Filters.Add <GlobalExceptionFilter>();
                options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider());
            });

            services.AddSession();
            services.AddHttpContextAccessor();

            services.AddOptions();

            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection"));

            GlobalContext.Services        = services;
            GlobalContext.ServiceProvider = services.BuildServiceProvider();
            GlobalContext.Configuration   = Configuration;
        }
Beispiel #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //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;
            //});
            //Ìí¼ÓSignalR
            services.AddSignalR();

            services.AddMvc(options => {
                options.Filters.Add(new Extensions.AuthorizationActionFilter());
            }).AddNewtonsoftJson();

            services.AddSession();
            services.AddMemoryCache();
            //
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //Ìí¼ÓSession·ÃÎÊÈÝÆ÷
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //×¢²á×Ô¶¨Òå·þÎñ
            services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions()
            {
                Configuration = Configuration.GetSection("Cache:ConnectionString").Value,
                InstanceName  = Configuration.GetSection("Cache:InstanceName").Value
            }));
            Framework.Services.ServiceContext.RegisterServices(services.BuildServiceProvider());
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            _logService.Write("Application_Start");

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

            services.AddHttpContextAccessor();

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            services.AddControllersWithViews()
            .AddNewtonsoftJson();
            services.AddRazorPages();

            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
        }
Beispiel #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            AddAssembly(services, "CMSCore");

            services.AddMemoryCache();
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <LoginModel.LoginModel>();
            services.AddSingleton <ICacheService, MemoryCacheService>();
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.ContractResolver      = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                options.SerializerSettings.DateFormatString      = "yyyy-MM-dd HH:mm:ss";
            });
            services.AddSwagger();


            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });

            services.AddControllers();
        }
Beispiel #19
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <ApplicationDbContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     //options.UseMySql("server=localhost:8080; port=3306; database=ez; user=root; password=P@ssword"));
     services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
     {
         // Password settings
         options.Password.RequireDigit           = true;
         options.Password.RequiredLength         = 8;
         options.Password.RequiredUniqueChars    = 2;
         options.Password.RequireLowercase       = true;
         options.Password.RequireNonAlphanumeric = false;
         options.Password.RequireUppercase       = true;
     })
     .AddEntityFrameworkStores <ApplicationDbContext>()
     .AddDefaultTokenProviders();
     services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     // Add application services.
     services.AddSingleton <HtmlEncoder>(
         HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                                   UnicodeRanges.Arabic }));
     services.AddScoped <IUserHandler, UserHandler>();
     services.AddTransient <IEmailSender, EmailSender>();
     services.AddAutoMapper();
     services.AddMvc();
 }
Beispiel #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigurePoco <FileConfig>(Configuration.GetSection("FileConfig"));
            services.ConfigurePoco <AppSetting>(Configuration.GetSection("AppSetting"));
            //services.ConfigurePoco<SmsSetting>(Configuration.GetSection("SmsSetting"));


            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[]
            {
                UnicodeRanges.BasicLatin,
                UnicodeRanges.Arabic
            }));

            services.AddAutoMapper(typeof(MappingProfile));


            services.AddScoped <IUserResolverService, UserResolverServiceByHttpContext>();
            services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
            services.AddScoped <IDbConnection>(options => new SqlConnection(Configuration.GetConnectionString("Default")));


            services
            .AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 6;

                //For generate integer number
                options.Tokens.ChangePhoneNumberTokenProvider = "Phone";
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath   = "/Account/Login";
                options.Cookie.Name = ".Amlak";
            });


            services.Configure <RouteOptions>(options =>
            {
                options.AppendTrailingSlash = true;
                options.LowercaseUrls       = true;
            });

            services.AddScoped <HouseRepository>();
            services.AddScoped <CategoryRepository>();
            services.AddScoped <OptionRepository>();
            services.AddScoped <PagesRepository>();
            services.AddScoped <NewsRepository>();

            services.AddMemoryCache();

            services.AddMvc();
        }
Beispiel #21
0
        //This method gets called by the runtime.Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => false;//不需要检查cookie
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).SetCompatibilityVersion(CompatibilityVersion.Latest).ConfigureApiBehaviorOptions(opt =>
            {
                opt.SuppressModelStateInvalidFilter = true;
            }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            services.AddControllersWithViews(
                option =>
            {
                // option.Filters.Add<GlobalExceptionFilter>();//全局错误处理
            })
            .AddRazorRuntimeCompilation();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            services.AddHttpClient();
            services.AddHttpClient <HeadService>();
        }
Beispiel #22
0
        static Helpers()
        {
            var encoderSettings = new TextEncoderSettings(UnicodeRanges.All);

            encoderSettings.ForbidCharacters('*', '_', '`');
            TelegramMarkdownEncoder = HtmlEncoder.Create(encoderSettings);
        }
Beispiel #23
0
        public async Task <IActionResult> Comment(CommentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Post), new { id = model.PostId }));
            }

            var post = _blogRepository.GetPost(model.PostId);
            var user = await _userManager.GetUserAsync(User);

            var encodedComment = HtmlEncoder.Create().Encode(model.Message);

            post.Comments = post.Comments ?? new List <Comment>();
            post.Comments.Add(new Comment
            {
                Id         = Guid.NewGuid().ToString().Replace("-", string.Empty).ToLowerInvariant(),
                Message    = encodedComment,
                DatePosted = DateTime.Now,
                Username   = user.UserName,
                Gravator   = user.ImageUrl
            });
            _blogRepository.UpdatePost(post);
            await _blogRepository.SaveChangesAsync();

            return(RedirectToAction(nameof(Post), new { id = model.PostId }));
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false; // KHÔNG BAO GIỜ ĐỂ LÀ TRUE, LÀM ƠN
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // ----- Phần này để sử dụng Session. Hướng dẫn tại : https://www.c-sharpcorner.com/article/all-about-session-in-asp-net-core/
            services.AddDistributedMemoryCache();
            services.AddSession(p =>
            {
                p.IdleTimeout = TimeSpan.FromMinutes(30);
            });
            // ----- //

            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] {
                UnicodeRanges.All
            }));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext <CosmeticShopDbContext>(dbContextOptionBuilder => dbContextOptionBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opt =>
            {
                opt.LoginPath        = "/Admin/Login";
                opt.AccessDeniedPath = "/Home/AccessDenied";
                opt.LogoutPath       = "/KhachHang/Logout";
            });
            services.AddSingleton <IConfiguration>(Configuration);
        }
Beispiel #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddRazorPages();
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddIdentity <User, IdentityRole>(options =>
            {
                options.SignIn.RequireConfirmedAccount  = true;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <MyDbContext>()
            .AddDefaultTokenProviders();
            //.AddErrorDescriber<LocalizedIdentityErrorDescriber>();
            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Auth/AccessDenied");
                options.LoginPath        = new PathString("/Auth/Login");
            });
            services.AddDbContext <MyDbContext>(opt =>
            {
                opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("GlobalBusiness.DataAccess"));
            }, ServiceLifetime.Transient);
            services.AddHttpContextAccessor();
            services.AddDataAccess();
            services.AddInfrastructure();
            services.AddSingleton <IEmailSender, EmailSender>();
            //ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("fa");

            services.AddScoped <IRolePermissionService, RolePermissionService>();
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();

            services.AddScoped <IUserPermissionHelper, UserPermissionHelper>();

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")
                                                      //    , new SqlServerStorageOptions
                                                      //{
                                                      //    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                                                      //    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                                                      //    QueuePollInterval = TimeSpan.Zero,
                                                      //    UseRecommendedIsolationLevel = true,
                                                      //    DisableGlobalLocks = true
                                                      //}
                                                      ));

            services.AddHangfireServer(opt => opt.WorkerCount = 1);


            services.AddSingleton <HtmlEncoder>(
                HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                                          UnicodeRanges.Arabic }));
        }
Beispiel #26
0
        public static void UseEasyFrameWork(this IServiceCollection services, IConfiguration configuration)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <RazorViewEngineOptions>, PluginRazorViewEngineOptionsSetup>());

            //services.Replace(ServiceDescriptor.Transient<IControllerActivator, Mvc.Controllers.ServiceBasedControllerActivator>());
            //services.TryAddEnumerable(ServiceDescriptor.Transient<IActionDescriptorProvider, ActionDescriptorProvider>());
            services.TryAddSingleton <IPluginLoader, Loader>();


            services.TryAddScoped <IAuthorizer, DefaultAuthorizer>();

            services.TryAddTransient <ICookie, Cookie>();
            services.TryAddTransient <IUserService, UserService>();
            services.TryAddTransient <IRoleService, RoleService>();
            services.TryAddTransient <IUserRoleRelationService, UserRoleRelationService>();
            services.TryAddTransient <IPermissionService, PermissionService>();
            services.TryAddTransient <IDataDictionaryService, DataDictionaryService>();
            services.AddScoped <ILanguageService, LanguageService>();
            services.TryAddTransient <IEncryptService, EncryptService>();
            services.AddSingleton <IOnModelCreating, EntityFrameWorkModelCreating>();

            services.AddTransient <IViewRenderService, ViewRenderService>();
            services.AddTransient <INotificationManager, NotificationManager>();
            services.AddTransient <INotifyService, EmailNotifyService>();
            services.AddTransient <INotifyService, RazorEmailNotifyService>();
            services.AddTransient <IPluginLoader, Loader>();
            services.AddTransient <IRuleManager, RuleManager>();
            services.AddTransient <IRuleProvider, CommonMethodsRuleProvider>();
            services.AddTransient <IRuleProvider, ValueOfRuleProvider>();
            services.AddTransient <IRuleProvider, DateRuleProvider>();
            services.AddTransient <IRuleProvider, MoneyRuleProvider>();
            services.AddTransient <IScriptExpressionEvaluator, ScriptExpressionEvaluator>();
            services.AddTransient <WebClient>();

            services.AddSingleton <ICacheProvider, DefaultCacheProvider>();
            services.AddTransient <ILocalize, Localize>();

            services.ConfigureCache <ScriptExpressionResult>();
            services.ConfigureCache <ConcurrentDictionary <string, ConcurrentDictionary <string, LanguageEntity> > >();

            services.AddScoped <IAuthorizationHandler, RolePolicyRequirementHandler>();
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

            services.ConfigureStateProvider <CurrentCustomerStateProvider>();
            services.ConfigureStateProvider <CurrentUserStateProvider>();
            services.ConfigureStateProvider <HostingEnvironmentStateProvider>();

            services.ConfigureMetaData <UserEntity, UserMetaData>();
            services.ConfigureMetaData <DataDictionaryEntity, DataDictionaryEntityMetaData>();
            services.ConfigureMetaData <LanguageEntity, LanguageEntityMetaData>();
            services.ConfigureMetaData <Permission, PermissionMetaData>();
            services.ConfigureMetaData <RoleEntity, RoleMetaData>();
            services.ConfigureMetaData <UserRoleRelation, UserRoleRelationMetaData>();


            services.Configure <CDNOption>(configuration.GetSection("CDN"));
            services.Configure <CultureOption>(configuration.GetSection("Culture"));

            services.AddDataProtection();
        }
        private static HtmlEncoder CreateHtmlEncoder()
        {
            var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);

            settings.AllowCharacter('\u2014');  // allow EM DASH through
            return(HtmlEncoder.Create(settings));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddErrorDescriber <LocalizedIdentityErrorDescriber>();

            services.AddSingleton(HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin, UnicodeRanges.Latin1Supplement, UnicodeRanges.LatinExtendedA }));
            services.AddLocalization(options => options.ResourcesPath = "Resources");



            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();
            services.AddAutoMapper();

            services.AddScoped <IPersonelRepository, PersonelRepository>();
            services.AddScoped <IPuantajRepository, PuantajRepository>();
            services.AddScoped <ISecenekListesiRepository, SecenekListesiRepository>();
            services.AddScoped <IUnvanRepository, UnvanRepository>();
            services.AddScoped <IHesaplamaRepository, HesaplamaRepository>();

            services.AddScoped <IUnitOfWork, UnitOfWork>();
        }
Beispiel #29
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMemoryCache();
     //services.AddMvc();
     services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });
     services.AddSingleton <ILog, Log>();
     services.AddSingleton <IUserService, UserService>();
     services.AddSingleton <IAccountService, AccountService>();
     services.AddSingleton <IPaymentService, PaymentService>();
     services.AddSingleton <IRecommentService, RecommentService>();
     services.AddSingleton <IOrderService, OrderService>();
     services.AddSingleton <IClickLogService, ClickLogService>();
     services.AddSingleton <IProfitService, ProfitService>();
     services.AddCors(options =>
     {
         options.AddPolicy("any", builder =>
         {
             builder.AllowAnyOrigin() //允许任何来源的主机访问
             .AllowAnyMethod()
             .AllowAnyHeader()
             .AllowCredentials();//指定处理cookie
         });
     });
     //解决unicode编码问题
     services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
     services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     services.AddHttpContextAccessor();
 }
Beispiel #30
0
        // ConfigureServices is invoked before Configure
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            services.AddIdentity <User, Role>()
            .AddUserStore <RepositoryUserStore>()
            .AddRoleStore <NullRoleStore>()
            .AddClaimsPrincipalFactory <DiscussionUserClaimsPrincipalFactory>()
            .AddDefaultTokenProviders();

            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs));
            services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });

            services.AddDataServices(_appConfiguration, _loggerFactory.CreateLogger <Startup>());

            services.AddAuthorization();
            services.ConfigureApplicationCookie(options => options.LoginPath = "/signin");
            services.Configure <IdentityOptions>(options =>
            {
                // 我们在 SigninUserViewModel 中的 PasswordRules 类中进行验证
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireDigit           = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;

//                options.User.RequireUniqueEmail = true;
            });
        }