C# – ASP.NET Core 3.1 – HTTP Error 500.30 – ANCM In-Process Start Failure

asp.net-coreasp.net-core-webapic

I am configuring net core web api using 3.1 version. I already checked this question here but no one of answers worked with my case.

I try to configure web api with net core ver 3.1. Another app with simmiliar configuration and same version of packages works as well with same iis express on my pc.

Here is my Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        readonly string AllowSpecificOrigins = "_allowSpecificOrigins";


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(AllowSpecificOrigins,
                builder =>
                {
                    builder.AllowCredentials().AllowAnyMethod().AllowAnyHeader().WithOrigins("http://localhost:4200");
                });
            });

            services.AddControllers()
                .AddNewtonsoftJson();

            services.AddScoped<IAccountRepository, AccountRepository>();
            services.AddScoped<IDocsRepository, DocsRepository>();

            services.AddDbContext<LibContext>(options =>
                options.UseNpgsql(Configuration.GetConnectionString("LibraryDatabase"), x => x.UseNetTopologySuite()));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false; 
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = AuthOptions.ISSUER,
                        ValidateAudience = true,
                        ValidAudience = AuthOptions.AUDIENCE,
                        ValidateLifetime = true,
                        IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
                        ValidateIssuerSigningKey = true
                    };                  
                });
            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                //password settings
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;

                options.User.RequireUniqueEmail = true;

                //lockout settings
                options.Lockout.AllowedForNewUsers = true;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
            })
                .AddEntityFrameworkStores<LibContext>()
                .AddUserManager<UserManager<ApplicationUser>>()
                .AddDefaultTokenProviders();

            services.AddSignalR();

        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(AllowSpecificOrigins); //DEV MODE!           
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Library")),
                RequestPath = new PathString("/Library")
            });
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();                
            });
        }
    }

Seems like i got no typos in my appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "LibraryDatabase": "Host=localhost;Port=5432;Database=librarydb;Username=postgres;Password=mypasshere"
  }
}

My app.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="Library\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.0" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="2.2.0" />
    <PackageReference Include="ProjNET4GeoAPI" Version="1.4.1" />
  </ItemGroup>


</Project>

Event viewer throw 2 errors, but i cant figure out what is wrong. Errors:

Application '/LM/W3SVC/2/ROOT' with physical root 'my app folder' has exited from Program.Main with exit code = '0'. First 30KB characters of captured stdout and stderr logs:
Programm starts

Application '/LM/W3SVC/2/ROOT' with physical root 'my app folder' failed to load coreclr. Exception message:
CLR worker thread exited prematurely

Thanks for your time

Best Answer

Ok, i think i found the answer. It has worked in my case!

Problem interesting with program main.cs not with this configuration, they shown good. There is a few case to happining this error

Case1- While migrating to .net core 3.1 from other core versions. Using kestrel with IHostBuilder. Don't use this

            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        //..
                    })
                    .UseStartup<Startup>();
                })
            .Build();

instead use this style. (CreateHostBuilder)

            var host = CreateHostBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory()).Build();
            host.Run();

//..

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureKestrel(serverOptions =>
    {
        serverOptions.Limits.MaxConcurrentConnections = 100;
        serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
        serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
        serverOptions.Limits.MinRequestBodyDataRate =
            new MinDataRate(bytesPerSecond: 100,
                gracePeriod: TimeSpan.FromSeconds(10));
        serverOptions.Limits.MinResponseDataRate =
            new MinDataRate(bytesPerSecond: 100,
                gracePeriod: TimeSpan.FromSeconds(10));
        serverOptions.Limits.KeepAliveTimeout =
            TimeSpan.FromMinutes(2);
        serverOptions.Limits.RequestHeadersTimeout =
            TimeSpan.FromMinutes(1);
    })
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>();
});

Case 2- Program.cs couldn't find Logger file or configuration file. It maybe couldn't reach to folder file permission etc. Check it with try catch in main function.

case 3- There is no or miss-configured AspNetCoreModuleV2 for InProcess mode

Generally 1 is the right case for this error but interested with 2 and 3