隨着技術的不斷拓展更新,咱們所使用的技術也在不斷地升級優化,項目的框架也在不斷地升級,本次講解 .net core 2.1 升級到3.1所須要注意的事項;web
當項目框架升級後,全部的Nuget引用也會對應變化,這些根據本身的框架所使用的技術對應作升級便可,這裏不作過多贅述;redis
其次就是要修改 Program.cs 文件,這裏把修改前的和修改後的統一貼出代碼作調整,代碼以下:json
2.1版本的文件代碼:api
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using System; namespace S2_Xxxx_XxxNetApi { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); Console.WriteLine("接口啓動成功"); // QuartzHelper.ExecuteInterval<Test>(200); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) //.UseUrls("http://*:5000")//發佈時須要註釋 .UseStartup<Startup>(); } }
3.1版本的文件代碼跨域
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System; namespace S2_Cggc_PmsNetApi { /// <summary> /// 啓動 /// </summary> public class Program { /// <summary> /// 啓動 /// </summary> public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); Console.WriteLine("接口啓動成功"); } /// <summary> /// 啓動 /// </summary> public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
而後就是Startup文件,代碼以下:瀏覽器
2.1版本文件代碼:cookie
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Impl; using S2_Xxxx_XxxNetApi; using System.Linq; namespace S2_Xxxx_XxxNetApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void 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; }); //調度任務註冊 services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();//註冊ISchedulerFactory的實例。 string conn = Configuration.GetSection("AppSettings:ConnectString").Value; MySqlHelper.Conn = conn; string orclconn = Configuration.GetSection("AppSettings:OrclConnectString").Value; OracleHelper.connectionString = orclconn; string redisconn = Configuration.GetSection("AppSettings:RedisConnectString").Value; RedisHelper.SetCon(redisconn); RedisHelper.BuildCache(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); //跨域支持 services.AddCors(options => { options.AddPolicy("CorsPolicy", corsBuild => corsBuild.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDistributedMemoryCache();//啓用session以前必須先添加內存 //services.AddSession(); services.AddSession(options => { options.Cookie.Name = ".AdventureWorks.Session"; options.IdleTimeout = System.TimeSpan.FromSeconds(1200);//設置session的過時時間 options.Cookie.HttpOnly = true;//設置在瀏覽器不能經過js得到該cookie的值 }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Version = "v1", Title = "接口文檔" }); options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }); } // 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.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); //app.usehets(); } app.UseSession(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI文檔"); }); //跨域支持 app.UseCors("CorsPolicy"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
3.1版本文件代碼:session
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Quartz; using Quartz.Impl; using System; namespace S2_Cggc_PmsNetApi { /// <summary> /// 啓動 /// </summary> public class Startup { /// <summary> /// 啓動 /// </summary> public Startup(IConfiguration configuration) { Configuration = configuration; } /// <summary> /// 啓動 /// </summary> public IConfiguration Configuration { get; } /// <summary> /// 啓動 /// </summary> public void ConfigureServices(IServiceCollection services) { //啓用session以前必須先添加內存 services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = ".AdventureWorks.Session"; options.IdleTimeout = System.TimeSpan.FromSeconds(1200);//設置session的過時時間 options.Cookie.HttpOnly = true;//設置在瀏覽器不能經過js得到該cookie的值 }); services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => false;//這裏要改成false,默認是true,true的時候session無效 options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); //註冊過濾器 services.AddSingleton<ApiResultFilterAttribute>(); services.AddSingleton<ApiExceptionFilterAttribute>(); services.AddMvc( config => { config.EnableEndpointRouting = false; config.Filters.AddService(typeof(ApiResultFilterAttribute)); config.Filters.AddService(typeof(ApiExceptionFilterAttribute)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(); //services.AddMvc(options => { options.Filters.Add<ResultFilterAttribute>(); }); services.AddSwaggerDocument(); //註冊Swagger 服務 services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); //調度任務註冊 services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();//註冊ISchedulerFactory的實例。 QuartzHelper.AddJobForSeconds<Deduction>(); QuartzHelper.Start(); } /// <summary> /// 啓動 /// </summary> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSession(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors("any"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); app.UseOpenApi(); //添加swagger生成api文檔(默認路由文檔 /swagger/v1/swagger.json) app.UseSwaggerUi3();//添加Swagger UI到請求管道中(默認路由: /swagger). app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
作了對應調整後,編譯後檢查是否還有錯誤提示,便可升級成功,可能有些控制器裏面的屬性寫法也會有些變化,這個尚未具體深刻研究,歡迎小夥伴們作補充,我將虛心接受你們的意見,感謝~app