Startup configuration for getting started with NetCore 2.0 MVC

Keywords: Programming Attribute Lambda JSON Database

Just contacted netcore, the following configuration instructions I am using and some points to be injected

1. I don't want to use constructor injection in my project, so I refer to the third-party Autofac package to manage my service. In the controller, I just need to create public iClass class{get;set;}

2. I use dll reflection to inject service,

Note the following code: var files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.BLL.dll"); because my business layer is in BLL, I only need to search the BLL file in the root directory for injection

3. If Areas is used in the project, the following code needs to be added

  app.UseMvc(routes =>
            {
                routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");//Controller hierarchy
               

If you need to build areas as a separate project, you need the following code in configure services (iservicecollection services), which is to inject controller s from subprojects into the main project

            #Called when region MVC region sub project
            var manager = new ApplicationPartManager();
            files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.Web.dll");//Get all web.dll
            if (files != null && files.Length > 0)
            {
                foreach (var file in files)
                {
                    manager.ApplicationParts.Add(new AssemblyPart(Assembly.LoadFrom(file)));
                }
            }
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            var feature = new ControllerFeature();
            manager.PopulateFeature(feature);
            #endregion

Add the following code to the attribute generate event generate event post build event in the subproject

mkdir "$(SolutionDir)$(SolutionName).Web\Areas\{AreaName}\Views"
xcopy "$(ProjectDir)Views" "$(SolutionDir)$(SolutionName).Web\Areas\{AreaName}\Views" /S /E /C /Y

 

 

 



    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public Autofac.IContainer ApplicationContainer;

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider 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;
            });
            //Read profile
            ApplicationEnvironments.Site = Configuration.GetSection("SiteConfig").Get<SiteConfig>();
          
            //httpContext if you need httpContext in dll layer, you need to use methods
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //Attribute injection
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc(config => {
                config.Filters.Add<CustomExceptionFilter>();
      
            }
            )
            //Global configuration Json serialization
        .AddJsonOptions(options =>
        {
            //Ignore circular references
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //key without hump
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            ////Format time
            //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
        }
        )
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddSessionStateTempDataProvider();
            #region / / the method to be used for authentication
            services.AddSession(options=> {
                options.Cookie.HttpOnly = true;
              
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.IdleTimeout = TimeSpan.FromMinutes(ApplicationEnvironments.Site.SessionTimeout);
            });
           
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.DataProtectionProvider= DataProtectionProvider.Create(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+ "/shared-auth-ticket-keys/"));
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.Path = "/";
                options.LoginPath = new PathString("/login");
                options.AccessDeniedPath = new PathString("/Forbidden"); //Forbidden access path: when a user attempts to access a resource but fails to pass any authorization policy of the resource, the request will be redirected to this relative path.
               // Options. Slidingexpiration = false; / / cookies can be divided into permanent and temporary. Temporary means that it is only valid in the current browser process. Once the browser is closed, it will fail (deleted by the browser). Permanent means that the cookie specifies an expiration time. Until this time, the cookie will remain valid (the browser has always recorded the existence of the cookie). The function of slidingexpression is to instruct the browser to store the cookie as a permanent cookie, but it will automatically change the expiration time so that the user will not be active after login, but will automatically log off after a period of time. That is to say, when you log in at 10:00, the TimeOut set by the server is 30 minutes. If the slidingexperiation is false, you must log in again after 10:30. If it is true, you open a new page at 10:16, and the server will notify the browser to change the expiration time to 10:46. For more detailed instructions, please refer to MSDN's documents.
            });
            #endregion
            ApplicationEnvironments.DefaultSession = new BaseController();
            //Database driven injection
            if (ApplicationEnvironments.Site.IsUseEF)
            {
                services.AddScoped<IDbRepository, EFRepository>();
            }
            else
            {
                services.AddScoped<IDbRepository, AdoRepository>();
            }
            //Cache injection
            if (ApplicationEnvironments.Site.IsUseRedis)
            {
                services.AddSingleton<ICacheService,RedisService>();
            }
            else
            {
                services.AddSingleton<ICacheService,MemoryService>();
            }
            //service layer injection
              var files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.BLL.dll");
            if (files != null && files.Length > 0)
            {
                foreach (var file in files)
                {
                    foreach (var item in GetClassName(file))
                    {
                        foreach (var typeArray in item.Value)
                        {
                            services.AddScoped(typeArray, item.Key);
                        }
                    }
                }
               
            }


            #Region autoface attribute injection 
            var builder = new Autofac.ContainerBuilder();
            builder.Populate(services);
            #Called when region MVC region sub project
            var manager = new ApplicationPartManager();
            files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.Web.dll");//Get all web.dll
            if (files != null && files.Length > 0)
            {
                foreach (var file in files)
                {
                    manager.ApplicationParts.Add(new AssemblyPart(Assembly.LoadFrom(file)));
                }
            }
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            var feature = new ControllerFeature();
            manager.PopulateFeature(feature);
            #endregion

            //Adopt attribute injection controller
            builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();
            this.ApplicationContainer = builder.Build();
            return new AutofacServiceProvider(this.ApplicationContainer);
           
            #endregion
            //Cross domain access

            //services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins("http://a.local.com:50307", "http://b.local.com:63455")));
            //Use this for cross domain authentication
            //services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins("http://a.local.com:50307", "http://b.local.com:63455").AllowCredentials()));
        }
        private static Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.LoadFrom(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    if (item.IsGenericType) continue;
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
        
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //app.UseBrowserLink();
                //app.UseDeveloperExceptionPage();
                ApplicationEnvironments.IsDevelopment = true;
            }
            else
            {
                //app.UseExceptionHandler("/Home/Error");
                //app.UseHsts();
                ApplicationEnvironments.IsDevelopment = false;
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseSpaStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseAuthentication();
            
            app.UseExceptionHandler("/Home/Error");//error handling
            //app.UseErrorHandling();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");//Controller hierarchy
               
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });
            
            //Add httpcontext class
            AppHttpContext.Configure(app.ApplicationServices.
     GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>());
            

            //nginx reverse proxy
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();
            app.UseStatusCodePages();//Use HTTP error code page
        }

    }

Posted by powerspike on Wed, 04 Dec 2019 01:09:58 -0800