9

I am configuring an ASP.NET Core 3.1 Web API. I already checked this question here but no one of answers worked with my case.

Another app with similar 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 can't figure out what is wrong:

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:
Program 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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mateech
  • 1,010
  • 1
  • 11
  • 26
  • 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 \.vs\Comma\config\applicationhost.config Please, have a look that in this file is properly registered AspNetCoreModuleV2 – Vic May 08 '20 at 15:28

9 Answers9

3

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

Hamit YILDIRIM
  • 4,224
  • 1
  • 32
  • 35
3

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.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
3

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.
user1439090
  • 792
  • 5
  • 12
  • 33
3

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.

Thinira
  • 361
  • 3
  • 8
1

In looking for a solution to my problem I came across this post. I am receiving the exact same error as you basically because I am also trying to serve up static files using PhysicalFileProvider from a network location. In my case it runs fine when I debug in localhost... but upon deployment I get your error as well. I think this line is what is causing your specific issue:

       app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Library")),
            RequestPath = new PathString("/Library")
        });

I would try commenting out that block to see if the error persists.

Anthony Griggs
  • 1,469
  • 2
  • 17
  • 39
0

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>
Alex Alvarez
  • 371
  • 3
  • 6
0

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

websplee
  • 187
  • 1
  • 7
0

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

Eternal21
  • 4,190
  • 2
  • 48
  • 63
0

You can check if the hosting folder "Resources" is created in the IIS:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Resources")),
    RequestPath = "/Resources"
});
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77