2

I have a big problem with an application. When I use IIS Express, everything works fine, but if I start the app with IIS (both with or without Visual Studio), the Program.cs and Startup.cs are ignored so the app is not working.

This happen both with .NET Core 2.2 and .NET Core 3.1 and also with Razor Pages or MVC projects.

The strange thing is that IIS was working until yesterday and I haven't done any changes, only a computer restart between two days. This both in my notebook and desktop PC.

I don't understand why but this is driving me crazy. Do you have any suggestions for solve the issue?

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args)
            .Build()
            .Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs

    public const string GenericCookieScheme = "XXX";
    public const string AuthSecret = "XXX";

    public Startup(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.AddRazorPages(options =>
        {
            options.Conventions.AuthorizePage("/Pages");
            options.Conventions.AllowAnonymousToFolder("/Pages/Login");
        });

        services.AddSession();

        services.AddControllersWithViews().AddRazorRuntimeCompilation();

        services.AddSingleton(Configuration.GetSection("AppSettings").Get<AppSettings>());
        #region SERVER
        services.AddEntityFrameworkSqlServer()
            .AddDbContext<DbConfigContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ConfigContainer")));

        services.AddEntityFrameworkSqlServer()
            .AddDbContext<DbDataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DataContainer")));

        services.AddScoped<ITenantProvider, TenantProvider>();
        services.AddScoped<IUserProvider, UserProvider>();
        services.AddTransient<IDbContextFactory, DbContextFactory>();
        DbDataContext.Init();
        #endregion

        #region AUTHENTICATION
        services.AddAuthentication(o =>
        {
            o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.AccessDeniedPath = new PathString("/Login");
            options.LoginPath = new PathString("/Login");
        });
        #endregion

        services.Configure<IISOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // 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();

        var defaultCulture = new CultureInfo("it-IT");
        var localizationOptions = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(defaultCulture),
            SupportedCultures = new List<CultureInfo> { defaultCulture },
            SupportedUICultures = new List<CultureInfo> { defaultCulture }
        };
        app.UseRequestLocalization(localizationOptions);

        app.UseHttpsRedirection();
        app.UseSession();
        app.UseAuthentication();

        app.UseStaticFiles();
        app.UseRequestLocalization("it-IT");

        app.UseRouting();

        app.UseRouter(r =>
        {
            r.MapGet(".well-known/acme-challenge/{id}", async (request, response, routeData) =>
            {
                var id = routeData.Values["id"] as string;
                var file = Path.Combine(env.WebRootPath, ".well-known", "acme-challenge", id);
                await response.SendFileAsync(file);
            });
        });

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });


        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var t = serviceScope.ServiceProvider.GetService<IHttpContextAccessor>();
            #region CONFIG CONTAINER
            if (!serviceScope.ServiceProvider.GetService<DbConfigContext>().AllMigrationsApplied())
            {
                serviceScope.ServiceProvider.GetService<DbConfigContext>().Database.Migrate();
            }
            serviceScope.ServiceProvider.GetService<DbConfigContext>().EnsureSeeded(env.WebRootPath);
            #endregion
            #region DATA CONTAINER

            var dbContextFactory = serviceScope.ServiceProvider.GetService<IDbContextFactory>();
            //var allTenants = serviceScope.ServiceProvider.GetService<SigfridAppConfigContext>().Tenants.First();
            var context = dbContextFactory.CreateDbContext(Configuration);
            if (!context.AllMigrationsApplied())
            {
                context.Database.Migrate();
            }
            //serviceScope.ServiceProvider.GetService<DbDataContext>().EnsureSeeded(Guid.Parse("A2DDFB53-3221-41E7-AD27-F3CD70EC5BAF"));
            #endregion
        }
    }
5
  • 2
    You may need the hosting bundle to host the ASP.NET Core app on IIS. see if this helps....dotnetcoretutorials.com/2019/12/23/… Commented Apr 25, 2020 at 0:18
  • Ignore? What is the error when you browse locally to IIS hosted site? Commented Apr 25, 2020 at 1:44
  • The browser said "404 not found", If I put a breakpoint both in startup.cs and program.cs the breakpoint is not hitted unless I switch to IIsExpress Commented Apr 25, 2020 at 8:32
  • Run some diagnostics docs.jexusmanager.com/tutorials/ancm-diagnostics.html and show the report as part of your question. Commented Apr 25, 2020 at 11:59
  • I tried Jexus Manager, it say the I haven't hosting bundle installed, but is false, others .net core projects is working. But, If I set the bindings, folders etc... in Jexus Manager it will work in iis. Commented Apr 25, 2020 at 14:07

2 Answers 2

3

Your checklist:

  • If IIS can handle requests for ASP.NET Core?
  • If IIS know that it needs to handle requests for ASP.NET Core?

For the first item

Please check if your IIS has the hosting bundle for ASP.NET Core installed.

Check it here:

IIS IIS modules

If not, download and install it here:

https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.3-windows-hosting-bundle-installer

The second item

Please check if there is a file named web.config located in your site's root folder:

Web.config

And its content shall be similar like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\Aiursoft.Account.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

Check the part: <aspNetCore> under <system.webServer>.

Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately everything is like your instructions, but is not working. The only difference is the processPath in web.config because visual studio at run put the full path of app.exe executable and the ports for iis
0

Ok I found the problem. Duplicated routes. I have a route called "/dashboard" with a controller in controller folder and the same in api folder. I don't know why there is no error of "duplicated route" but now it's fine. I'm sorry for having wasted your time with a stupid problem :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.