Получаю ошибку 500.30 при попытке запустить мой asp.net приложение Core 3.1 в azure

#asp.net-core #azure-web-app-service

#asp.net-core #azure-web-app-service

Вопрос:

У меня есть приложение, которое asp.net ядро 3.1 подключено к базе данных sql Server и файлу secrets. Я могу запустить все это локально, и это работает.

Я опубликовал свое приложение в Azure, перенес туда свою базу данных и создал хранилище ключей. Все они говорят, что они были успешными.

Когда я пытаюсь опубликовать свое приложение, оно сообщает «Настроено» для базы данных и хранилища ключей, и приложение успешно развертывается. Однако, когда оно перенаправляет меня на веб-сайт, где должно быть запущено мое приложение, я получаю ошибку 500.30.

Это ошибки, которые я получал вчера: (Я не уверен, что получаю сейчас, потому что, похоже, я не могу найти страницу в Azure, где я их нашел, и я потратил около 20 минут на ее поиски)

Ошибка # 1

 Application: w3wp.exe
CoreCLR Version: 4.700.20.26901
.NET Core Version: 3.1.6
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance')
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
   at RecipeCompendiumTool.Startup.ConfigureServices(IServiceCollection services) in C:UsersjuliesourcereposRecipeCompendiumToolStartup.cs:line 44
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at RecipeCompendiumTool.Program.Main(String[] args) in C:UsersjuliesourcereposRecipeCompendiumToolProgram.cs:line 16
  

Ошибка # 2

 Application '/LM/W3SVC/312799001/ROOT' with physical root 'D:homesitewwwroot' hit unexpected managed exception, exception code = '0xe0434352'. First 30KB characters of captured stdout and stderr logs:
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance')
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
   at RecipeCompendiumTool.Startup.ConfigureServices(IServiceCollection services) in C:UsersjuliesourcereposRecipeCompendiumToolStartup.cs:line 44
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at RecipeCompendiumTool.Program.Main(String[] args) in C:UsersjuliesourcereposRecipeCompendiumToolProgram.cs:line 16

Process Id: 6904.
File Version: 13.1.20169.6. Description: IIS ASP.NET Core Module V2 Request Handler. Commit: 62c098bc170f50feca15916e81cb7f321ffc52ff
  

Ошибка # 3

 Application '/LM/W3SVC/312799001/ROOT' with physical root 'D:homesitewwwroot' failed to load coreclr. Exception message:
CLR worker thread exited prematurely
Process Id: 6904.
File Version: 13.1.20169.6. Description: IIS ASP.NET Core Module V2 Request Handler. Commit: 62c098bc170f50feca15916e81cb7f321ffc52ff
  

Мой файл Startup.cs

         public IConfiguration Configuration { get; }
        public IWebHostEnvironment Environment { get; }

        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISServerDefaults.AuthenticationScheme);

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.Configure<FormOptions>(x => x.ValueCountLimit = 1000000000);

            services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
            services.AddTransient<IEmailService, EmailService>();
            services.AddSingleton<IEmailSender, EmailSender>();

            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddIdentity<RecipeCompendiumToolUser, IdentityRole>()
                .AddEntityFrameworkStores<RecipeCompendiumToolContext>()
                .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                    options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                });


            if (Environment.IsDevelopment())
            {
                services.AddRazorPages().AddRazorRuntimeCompilation();

                services.AddDbContext<RecipeCompendiumToolContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }
            else if (Environment.IsStaging())
            {
                services.AddRazorPages().AddRazorRuntimeCompilation();

                services.AddDbContext<RecipeCompendiumToolContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
            }
            else if (Environment.IsProduction())
            {
                services.AddDbContext<RecipeCompendiumToolContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("ProdConnection")));
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)//, RecipeCompendiumToolSeedData seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // TODO: The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            //seeder.InitializeSeedData();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
        }
    }
  

Комментарии:

1. Как видно из stacktrace, можете ли вы проверить наличие параметра с именем ‘implementationInstance’ в EmailConfiguration или EmailSender? По-видимому, этот параметр не добавлен в настройки вашего приложения / настройки хранилища ключей. И, скорее всего, именно поэтому вы получаете ошибку # 3 до тех пор, пока не появится еще несколько ошибок, которые скрыты за ошибками # 1 и 2.

2. Я возвращался к одному коммиту за раз, и было около 5 разных проблем — некоторые при запуске.cs (дублирующаяся строка и моя модель / вызов для инициализации начальных данных), различные. файлы json (при удалении раздела EmailConfiguration возникают ошибки), и по какой-то причине в автоматически сгенерированном файле _LoginPartial.cshtml, созданном при установке программного обеспечения Microsoft для идентификации. Я все еще работаю над первым и последним, но я исправил остальные.

3. Какая из ошибок, о которых вы упомянули, осталась? И какие из них вы удалили? Кроме того, вы проверяли параметр ‘implementationInstance’?

4. Я не знаю, какие ошибки остались — я искал по всему веб-сайту Azure и не могу найти, где я видел их в первую очередь. Если вы знаете, как я могу их найти, я обновлю то, что осталось.

Ответ №1:

Исправлено — могли быть и другие проблемы, но если вы развертываетесь в Azure с БД, убедитесь, что в настройках брандмауэра вашей БД для параметра «Разрешить службам и ресурсам Azure доступ к этому серверу» установлено значение «ДА».