1. 程式人生 > >NetCore 2.0 MVC入門之 Startup 配置

NetCore 2.0 MVC入門之 Startup 配置

剛接觸netcore, 以下我正在使用的配置說明以及需要注入的幾點

1.我在專案中因為不想使用建構函式注入,所以我引用了第三方的Autofac包來管理我的service,在controller中只需要 建立 public iClass class{get;set;}即可

2.service注入我採用的是dll反射進行注入,

     注意如下程式碼  var files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.BLL.dll"); 由於我的業務層都放在BLL中,所以我只需要搜尋根目錄下的BLL檔案進行注入即可

 3. 專案中如果使用了Areas ,需要新增以下程式碼

  app.UseMvc(routes =>
            {
                routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");//控制器分層
               

如果需要將areas單獨建成專案,需要在ConfigureServices(IServiceCollection services)中如下程式碼,該程式碼是將子專案中的controller注入到主專案中

            #region  mvc 區域分專案時呼叫
            var manager = new ApplicationPartManager();
            files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.Web.dll");//獲取所有的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

在子專案中屬性 ---》生成事件----》後期生成事件中新增如下程式碼

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;
            });
            //讀取配置檔案
            ApplicationEnvironments.Site = Configuration.GetSection("SiteConfig").Get<SiteConfig>();
          
            //httpcontext 如果在dll層需要用到httpContext則需要使用方法
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //屬性注入
            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc(config => {
                config.Filters.Add<CustomExceptionFilter>();
      
            }
            )
            //全域性配置Json序列化處理
        .AddJsonOptions(options =>
        {
            //忽略迴圈引用
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //不使用駝峰樣式的key
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            ////設定時間格式
            //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
        }
        )
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddSessionStateTempDataProvider();
            #region  //身份認證時需要使用的方法
            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"); //禁止訪問路徑:當用戶試圖訪問資源時,但未通過該資源的任何授權策略,請求將被重定向到這個相對路徑。
               // options.SlidingExpiration = false;  //Cookie可以分為永久性的和臨時性的。 臨時性的是指只在當前瀏覽器程序裡有效,瀏覽器一旦關閉就失效(被瀏覽器刪除)。 永久性的是指Cookie指定了一個過期時間,在這個時間到達之前,此cookie一直有效(瀏覽器一直記錄著此cookie的存在)。 slidingExpriation的作用是,指示瀏覽器把cookie作為永久性cookie儲存,但是會自動更改過期時間,以使使用者不會在登入後並一直活動,但是一段時間後卻自動登出。也就是說,你10點登入了,伺服器端設定的TimeOut為30分鐘,如果slidingExpriation為false,那麼10:30以後,你就必須重新登入。如果為true的話,你10:16分時打開了一個新頁面,伺服器就會通知瀏覽器,把過期時間修改為10:46。 更詳細的說明還是參考MSDN的文件。
            });
            #endregion
            ApplicationEnvironments.DefaultSession = new BaseController();
            //資料庫驅動注入
            if (ApplicationEnvironments.Site.IsUseEF)
            {
                services.AddScoped<IDbRepository, EFRepository>();
            }
            else
            {
                services.AddScoped<IDbRepository, AdoRepository>();
            }
            //快取注入
            if (ApplicationEnvironments.Site.IsUseRedis)
            {
                services.AddSingleton<ICacheService,RedisService>();
            }
            else
            {
                services.AddSingleton<ICacheService,MemoryService>();
            }
            //service 層注入
              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 AutoFac 屬性注入 
            var builder = new Autofac.ContainerBuilder();
            builder.Populate(services);
            #region  mvc 區域分專案時呼叫
            var manager = new ApplicationPartManager();
            files = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.Web.dll");//獲取所有的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

            //採用屬性注入控制器
            builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();
            this.ApplicationContainer = builder.Build();
            return new AutofacServiceProvider(this.ApplicationContainer);
           
            #endregion
            //跨域訪問

            //services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.WithOrigins("http://a.local.com:50307", "http://b.local.com:63455")));
            //跨域認證時使用此項
            //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");//錯誤處理
            //app.UseErrorHandling();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");//控制器分層
               
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });
            
            //新增httpcontext類
            AppHttpContext.Configure(app.ApplicationServices.
     GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>());
            

            //nginx反向代理
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();
            app.UseStatusCodePages();//使用HTTP錯誤內碼表
        }

    }