.net core 2.0项目升级3.1

前言

微软升级了.net core 3.1之后,原有的2.0项目如果升级的话,代码改动还是挺大的,主要涉及到引入的第三方包、Startup和Program的改动。不过微软改动之后的设计,比之前的更加友好了。

升级3.1改动的代码

Web项目的Program文件修改

  • 以下代码是Program.cs文件 .net core 2.0+的写法。
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace App.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build();
    }
}
  • 以下代码是Program.cs文件.net core 3.1的写法。
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace App.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        //.net core 2.2写法 升级为.net core 3.1
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    //webBuilder.UseKestrel();//kestrel主机
                    //webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                    //webBuilder.UseUrls("http://*:9101");
                    webBuilder.UseIIS();//iis 主机
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                })
                .UseNLog();
    }
}
  • 变动说明
  1. WebHost对象改为统一使用Host对象,命名空间:Microsoft.Extensions.Hosting。
  2. WebHostBuilder的创建有改动,改为在ConfigureWebHostDefaults中配置。
  3. Logging的配置从Startup迁移到Program了(示例代码配置的是NLog)。

Web项目的Startup修改

  • .net core 2.0写法
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;
using System.Net;

namespace App.Api
{
    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.AddMvc
                (
                    options =>
                    {
                        options.Filters.Add<ExceptionHandlerFilter>();
                    }
                )
                .AddJsonOptions
                (
                json =>
                {
                    json.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//统一设置JsonResult中的日期格式
                });
        }        
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="provider"></param>
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IApiVersionDescriptionProvider provider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            loggerFactory.AddNLog(); //添加NLog
            env.ConfigureNLog("NLog.config");//读取Nlog配置文件
            app.UseMvc();
        }
    }
}
  • .net core 3.1写法
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace App.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            JSON_DATETIME_TO_STRING_FORMAT = "yyyy-MM-dd HH:mm:ss";
        }
        private readonly string JSON_DATETIME_TO_STRING_FORMAT;
        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.AddControllers()
            .AddNewtonsoftJson(opts =>
            {
                opts.SerializerSettings.DateFormatString = JSON_DATETIME_TO_STRING_FORMAT;
            })
            .AddMvcOptions(options =>
            {
                options.Filters.Add<ExceptionHandlerFilter>();
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
  • 变动说明
  1. services.AddMvc被拆分成了AddControllers和AddMvcOptions。
  2. 如果还在使用Newtonsoft作为JsonResult的默认序列化器,设置Newtonsoft.Json的方式也发生变化了(AddNewtonsoftJson,应该是为自家的Text.Json让路)。
  3. 需要引入包Microsoft.Extensions.Hosting.Abstractions,因为env.IsDevelopment()的命名空间发生了变化。
  4. Configure中的UseMvc也被拆分了。

.Net技术交流QQ群

欢迎还在追逐.Net技术栈的战神和HR加入QQ群:70895254

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值