1. 程式人生 > >.Net Core 2.1 升級3.1 問題整理

.Net Core 2.1 升級3.1 問題整理

         隨著技術的不斷拓展更新,我們所使用的技術也在不斷地升級優化,專案的框架也在不斷地升級,本次講解 .net core 2.1  升級到3.1所需要注意的事項;

   當專案框架升級後,所有的Nuget引用也會對應變化,這些根據自己的框架所使用的技術對應做升級即可,這裡不做過多贅述;

其次就是要修改 Program.cs 檔案,這裡把修改前的和修改後的統一貼出程式碼做調整,程式碼如下:

2.1版本的檔案程式碼:

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版本檔案程式碼:

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版本檔案程式碼:

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?}"); });
        }
    }
}

做了對應調整後,編譯後檢查是否還有錯誤提示,即可升級成功,可能有些控制器裡面的屬性寫法也會有些變化,這個還沒有具體深入研究,歡迎小夥伴們做補充,我將虛心接受大家的意見,感謝~