随着技术的不断拓展更新,我们所使用的技术也在不断地升级优化,项目的框架也在不断地升级,本次讲解 .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?}"); });
        }
    }
}

做了对应调整后,编译后检查是否还有错误提示,即可升级成功,可能有些控制器里面的属性写法也会有些变化,这个还没有具体深入研究,欢迎小伙伴们做补充,我将虚心接受大家的意见,感谢~

03-13 00:02