简体   繁体   English

.NET Core program.cs 和 Startup.cs 未命中

[英].NET Core program.cs and Startup.cs not hit

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.当我使用 IIS Express 时,一切正常,但如果我使用 IIS 启动应用程序(使用或不使用 Visual Studio), Program.csStartup.cs将被忽略,因此应用程序无法运行。

This happen both with .NET Core 2.2 and .NET Core 3.1 and also with Razor Pages or MVC projects. .NET Core 2.2 和 .NET Core 3.1 以及 Razor 页面或 MVC 项目都会发生这种情况。

The strange thing is that IIS was working until yesterday and I haven't done any changes, only a computer restart between two days.奇怪的是,IIS一直工作到昨天,我没有做任何改动,只是两天之间重启了一次电脑。 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程序.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启动.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
        }
    }

Your checklist:你的清单:

  • If IIS can handle requests for ASP.NET Core?如果 IIS 可以处理 ASP.NET Core 的请求?
  • If IIS know that it needs to handle requests for ASP.NET Core?如果 IIS 知道它需要处理 ASP.NET Core 的请求?

For the first item对于第一项

Please check if your IIS has the hosting bundle for ASP.NET Core installed.请检查您的 IIS 是否安装hosting bundle for ASP.NET Core

Check it here:在这里检查:

信息系统 IIS 模块

If not, download and install it here:如果没有,请在此处下载并安装它:

https://do.net.microsoft.com/download/do.net-core/thank-you/runtime-as.netcore-3.1.3-windows-hosting-bundle-installer https://do.net.microsoft.com/download/do.net-core/thank-you/runtime-as.netcore-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> .检查部分: < <system.webServer> > 下的<aspNetCore> > 。

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.我有一个名为“/dashboard”的路由,controller 文件夹中有一个 controller,api 文件夹中有一个相同的路由。 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:)很抱歉在一个愚蠢的问题上浪费了你的时间:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 只要ASP.NET Core中有可用的program.cs / startup.cs,即可获取当前URL - Get Current URL as soon as available program.cs / startup.cs in ASP.NET Core ASP.NET 内核在 Program.cs 和 Startup.cs 中捕获并显示错误 - ASP.NET Core catch and display error inside Program.cs and Startup.cs .NET核心从Program.cs传递命令行Args到Startup.cs - .NET core Pass Commandline Args to Startup.cs from Program.cs ASP.NET Core 2 中的 Startup.cs 与 Program.cs - Startup.cs vs Program.cs in ASP.NET Core 2 在 startup.cs ConfigureServices 或 program.cs Main 方法中在 .NET Core 3.+ 中注册 IHostedService 时有区别吗? - Is there a difference when registering an IHostedService in .NET Core 3.+ in the startup.cs ConfigureServices or in program.cs Main method? 如何将 UserManager 注入 Program.cs 或 Startup.cs - How to inject UserManager to Program.cs or Startup.cs 如何解决从 Program.cs 调用 Startup.cs? - How to solve calling Startup.cs from Program.cs? .net 核心 Startup.cs CreateScope 或 BuildServiceProvider - .net core Startup.cs CreateScope or BuildServiceProvider 如何检索Program.cs中返回的访问令牌以在Startup.cs中可用? - How do I retrieve an access token returned in Program.cs to be available in Startup.cs? 如何访问在 startup.cs 中定义的 program.cs 中的 singleton 服务 - how to access a singleton service in program.cs which was defined in startup.cs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM