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错误代码页
        }

    }

猜你喜欢

转载自my.oschina.net/u/3049482/blog/2964907
今日推荐