Asp.net core 2.1 to Asp.net 3.0 upgrade

最后都变了- 提交于 2020-01-24 12:24:06

问题


I have a web api application which is working fine in 2.1. I am using same application to host in IIS on windows and without IIS on linux. Now I am trying to upgrade the application.

I have upgraded the nuget packages and project version successfully.Now when trying to debug app looks there is some problem in my congiruation startup class which is as below

public static void Main(string[] args)
{

            StartupShutdownHandler.BuildWebHost(args).Build().Run();
}


namespace MyApp
{
    public class StartupShutdownHandler
    {

        public static IWebHostBuilder BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args)
               .UseStartup<StartupShutdownHandler>();

        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public StartupShutdownHandler(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.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters(); //this is changed in 3.0
            services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);

            CorsRelatedPolicyAddition(services);
        }

        private void CorsRelatedPolicyAddition(IServiceCollection services)
        {
            var lstofCors = ConfigurationHandler.GetSection<List<string>>(StringConstants.AppSettingsKeys.CorsWhitelistedUrl);
            if (lstofCors != null && lstofCors.Count > 0 && lstofCors.Any(h => !string.IsNullOrWhiteSpace(h)))
            {                
                services.AddCors(options =>
                {
                    options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(lstofCors.ToArray()).AllowAnyMethod().AllowAnyHeader(); });
                });

            }
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(MyAllowSpecificOrigins);
            //app.UseMvc(); //this is changed in 3.0
            applicationLifetime.ApplicationStarted.Register(StartedApplication);
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
        }


        private void OnShutdown()
        {
             Logger.Debug("Application Shutdown");
        }

        private void StartedApplication()
        {
            Logger.Debug("Application Started");
        }
    }
}

I have tried chagned some lines which are commented as //this is changed in 3.0 but it doesn't work. Please identify the problem


回答1:


Following changes eventually work for 2.1 to 3.0 path. One manual change i am doing is updating newtonsoft to new builtin json type in all places where it doesn't break (e.g for one case i have to still use newtonsoft where i am serializing Formcollection and QueryCollection of the request)

namespace MyApp.Interfaces
{
    public class StartupShutdownHandler
    {

        public static IWebHostBuilder BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).
            ConfigureKestrel(serverOptions =>{}).UseIISIntegration()
            .UseStartup<StartupShutdownHandler>();

        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";


        public StartupShutdownHandler(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.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers(options => options.RespectBrowserAcceptHeader = true).AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters(); //updated            
            CorsRelatedPolicyAddition(services);
        }

        private void CorsRelatedPolicyAddition(IServiceCollection services)
        {
            var lstofCors = ConfigurationHandler.GetSection<List<string>>(StringConstants.AppSettingsKeys.CorsWhitelistedUrl);
            if (lstofCors != null && lstofCors.Count > 0 && lstofCors.Any(h => !string.IsNullOrWhiteSpace(h)))
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(lstofCors.ToArray()).AllowAnyMethod().AllowAnyHeader(); });
                });

            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseCors(MyAllowSpecificOrigins);
            app.UseEndpoints(endpoints =>
            {                
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });            
            applicationLifetime.ApplicationStarted.Register(StartedApplication);
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
        }


        private void OnShutdown()
        {
             Logger.Debug("Application Ended");
        }

        private void StartedApplication()
        {
            Logger.Debug("Application Started");
        }
    }
}


来源:https://stackoverflow.com/questions/58516574/asp-net-core-2-1-to-asp-net-3-0-upgrade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!