Example #1
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     ViewLocationExpander.ExpandViewLocations();
 }
Example #2
0
        public void ExpandViewLocations_ReturnsViewLocations()
        {
            ActionContext context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            ViewLocationExpanderContext expander = new ViewLocationExpanderContext(context, "Index", null, null, null, true);

            IEnumerable <String> expected = new[] { "/Views/{1}/{0}.cshtml", "/Views/Shared/{0}.cshtml" };
            IEnumerable <String> actual   = new ViewLocationExpander().ExpandViewLocations(expander, null);

            Assert.Equal(expected, actual);
        }
Example #3
0
        public void ExpandViewLocations_Area_ReturnsAreaLocations()
        {
            ActionContext context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            ViewLocationExpanderContext expander = new ViewLocationExpanderContext(context, "Index", null, null, null, true);

            context.RouteData.Values["area"] = "Test";

            IEnumerable <String> expected = new[] { "/Views/{2}/Shared/{0}.cshtml", "/Views/{2}/{1}/{0}.cshtml", "/Views/Shared/{0}.cshtml" };
            IEnumerable <String> actual   = new ViewLocationExpander().ExpandViewLocations(expander, Array.Empty <String>());

            Assert.Equal(expected, actual);
        }
        public void ExpandViewLocations_ReturnsViewLocations()
        {
            ActionContext actionContext         = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            ViewLocationExpanderContext context = new ViewLocationExpanderContext(actionContext, "Index", false);

            actionContext.ActionDescriptor.RouteConstraints = new List <RouteDataActionConstraint>();

            IEnumerable <String> expected = new[] { "/Views/{1}/{0}.cshtml", "/Views/Shared/{0}.cshtml" };
            IEnumerable <String> actual   = new ViewLocationExpander().ExpandViewLocations(context, null);

            Assert.Equal(expected, actual);
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            //services.AddApplicationInsightsTelemetry(Configuration);

            if (Global.UseMySql == false)
            {
                services.AddDbContext <AppDbContext>(options =>
                                                     options.UseSqlServer(
                                                         Configuration.GetConnectionString("defaultConnection"),
                                                         b => { b.MigrationsAssembly("www"); b.EnableRetryOnFailure(); }));
            }
            else
            {
                services.AddDbContext <AppDbContext>(options =>
                                                     options.UseMySql(
                                                         Configuration.GetConnectionString("defaultMysqlConnection"),
                                                         b => b.MigrationsAssembly("www")));
            }

            // Add Identity services to the services container.
            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength         = 6;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                //options.User.AllowedUserNameCharacters = null;
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();
            // Add cookie-based authentication to the request pipeline.
            services.ConfigureApplicationCookie(o =>
            {
                o.Cookie.HttpOnly = true;
                //o.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
#if !DEBUG
                o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
#else
                o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
#endif

                /*HttpOnly = HttpOnlyPolicy.Always,
                 * Secure = CookieSecurePolicy.Always,
                 * //OnAppendCookie = context =>
                 * //{
                 * //    context.CookieOptions.Expires = DateTimeOffset.Now.AddMinutes(10);
                 * //}*/
            });

            // Add response caching service...
            services.AddResponseCaching(options =>
            {
                options.UseCaseSensitivePaths = false;
                //options.MaximumBodySize = 64 * 1024 * 1024;
            });

            // Add MVC services to the services container.
            services
            .AddMvc(options =>
            {
                options.CacheProfiles.Add("Default",
                                          new CacheProfile()
                {
                    VaryByHeader    = "Host",
                    VaryByQueryKeys = new string[] { "skip" },
                    Location        = ResponseCacheLocation.Any,
                    Duration        = 24 * 60 * 60  // One day
                });
                options.CacheProfiles.Add("Never",
                                          new CacheProfile()
                {
                    VaryByHeader = "Host",
                    Location     = ResponseCacheLocation.None,
                    NoStore      = true
                });
            })
            // De-Camelizing JSON in ASP.NET Core...
            .AddJsonOptions(opt => {
                var resolver = opt.SerializerSettings.ContractResolver;
                if (resolver != null)
                {
                    var res            = resolver as DefaultContractResolver;
                    res.NamingStrategy = null;      // <<!-- this removes the camelcasing
                }
            })
            // Is Modular Web Application in vNext Possible?
            // https://github.com/aspnet/Mvc/issues/4572
            // https://github.com/thiennn/trymodular/tree/master/Modular/src
            // TODO: Application Parts in ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts
            .ConfigureApplicationPartManager(manager => manager.ApplicationParts.Clear())
            .AddApplicationPart(typeof(Startup).GetTypeInfo().Assembly)
            .AddApplicationPart(typeof(SiteApiController).GetTypeInfo().Assembly)
            .AddApplicationPart(typeof(DfideSiteSettings).GetTypeInfo().Assembly)
            .AddApplicationPart(typeof(VepSiteSettings).GetTypeInfo().Assembly);

            // Configure Razor view engine...
            services.Configure <RazorViewEngineOptions>(options =>
            {
                //options.FileProviders.Clear();
                options.FileProviders.Add(new CompositeFileProvider(
                                              new EmbeddedFileProvider(
                                                  typeof(DfideSiteSettings).GetTypeInfo().Assembly,
                                                  baseNamespace: "www.dfide.EmbeddedResources"
                                                  )));
                options.FileProviders.Add(new EmbeddedFileProvider(
                                              typeof(VepSiteSettings).GetTypeInfo().Assembly,
                                              baseNamespace: "www.vep.EmbeddedResources"
                                              ));
            });

            // Register application services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
            //services.AddTransient<ISiteSettings, SiteSettings>();

            // Inject context service.
            services.AddScoped <PerformanceProvider, PerformanceProvider>();
            services.AddScoped <WcmsAppContext, WcmsAppContext>();

            // Inject the view engine.
            //services.AddTransient/*AddScoped*//*AddSingleton*/<IRazorViewEngine, ViewEngine>();
            services.Configure <RazorViewEngineOptions>(options =>
            {
                var expander = new ViewLocationExpander(null);
                options.ViewLocationExpanders.Add(expander);
            });

            // Inject configuration service.
            services.AddSingleton(_ => Configuration);

            // only allow authenticated users

            /*var defaultPolicy = new AuthorizationPolicyBuilder()
             *  .RequireAuthenticatedUser()
             *  .Build();
             * services.AddMvc(setup =>
             * {
             *  setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
             * });*/

            // Register authorization policy...
            services.AddAuthorization(options =>
            {
                // inline policies
                options.AddPolicy(ClaimValueRole.Reader, policy =>
                {
                    policy.RequireClaim(UserClaimType.Role, ClaimValueRole.Reader);
                    //policy.RequireRole(Role.Reader);
                });
                options.AddPolicy(ClaimValueRole.Contributor, policy =>
                {
                    policy.RequireClaim(UserClaimType.Role, ClaimValueRole.Contributor);
                });
                options.AddPolicy(ClaimValueRole.Publicator, policy =>
                {
                    policy.RequireClaim(UserClaimType.Role, ClaimValueRole.Publicator);
                });
                options.AddPolicy(ClaimValueRole.Administrator, policy =>
                {
                    policy.RequireClaim(UserClaimType.Role, ClaimValueRole.Administrator);
                });
            });

            // Register resource authorization handlers...
            services.AddTransient <IAuthorizationHandler, SiteAuthorizationHandler>();
            services.AddTransient <IAuthorizationHandler, PageAuthorizationHandler>();
            services.AddTransient <IAuthorizationHandler, PostAuthorizationHandler>();
        }