刚接触netcore, 如下我正在使用的配置说明以及须要注入的几点nginx
1.我在项目中由于不想使用构造函数注入,因此我引用了第三方的Autofac包来管理个人service,在controller中只须要 建立 public iClass class{get;set;}便可web
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错误代码页 } }