剛接觸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錯誤代碼頁 } }