6
votes

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

7
it sounds like a crash in the module that 'joins' IIS Express with .net core platform... It's suppossed that you've restarted, and all the stuff we always do... The IIS "web.config" is in <PROJECT_FOLDER>\.vs\Comma\config\applicationhost.config Please, have a look that in this file is properly registered AspNetCoreModuleV2Vic

7 Answers

3
votes

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

3
votes

Following steps worked for me:

  1. Ensure that the app pool identity is Managed Code
  2. Ensure that IIS_IUSRS have permissions to website folder
  3. Ensure that logs folder is created in solution when it is published. If it is not available, we can also set stdoutLogEnabled to true as pointed in another answer by Alexander Protto. This step was the issue for my case.
  4. Ensure that target runtime is correct. If it is incorrect, the error would be different.
  5. Ensure that CreateDefaultBuilder(args) is added to startup.cs. This is similar to answer posted by Hamit.
1
votes

I had the same issue and tried everything. In the end, the issue was solved by fixing the appsetting.json file structure.

I Changed

stdoutLogEnabled="false" 

to

stdoutLogEnabled="true",

then the error message showed me where the error was.

1
votes

Also, Make sure to check the connection string as well, in "appsetting.json". In my case forgot to add escape characters to the data source. So, the correct way of having server name is \\MSSQLSERVER, but I had \MSSQLSERVER. Just a small mistake, but it took some time to figure it out.

0
votes

Thanks a lot. I was having the same problem, and I added the AspNetCoreHostingModel key and values to my VS project and It did the trick. I was looking the place from where I took it, but I cannot find it, but it was here in Stack Overflow. So, Thanks to the original contributor!!!

  <PropertyGroup>
      <TargetFramework>netcoreapp3.1</TargetFramework>
      <SignAssembly>false</SignAssembly>
      <OutputType>Exe</OutputType>
      <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
  </PropertyGroup>
0
votes

One of the things that I have tried and worked, as mentioned by other users is changing the hosting model to OutOfProcess. This, however, doesn't work all the time and I discovered some rather odd trick if you have swagger configured, manually copy the "project".xml file to the deployment root of your solution.

The later however should be backed up by checking your event viewer and you have this error System.IO.FileNotFoundException

0
votes

In my case changing app-pool account from NetworkService to LocalSystem fixed the problem.