简体   繁体   中英

.net core 2.1 web app works in visual studio but does not work when deployed to IIS in windows 10

I am new to .net core development and I am trying to deploy the web app .net core 2.1 to IIS in windows 10. I have followed all the steps including creating applicationpool 'No Managed Code' and everything worked fine. Later after 2 days it stopped working then I redoployed my project using the release type to Debug and here I am getting this exception displayed in the brower which is the same in the log file. 浏览网络应用程序时出错

However, the same app works fine in visual studio. My machine has the following .net packages installed. .Net Core Runtme 2.1.7(x64) .Net Core 2.1.7 - Windows Server Hosting .net Core Runtime 2.1.7(x86) .Net Core SDK 2.1.503 (x86) .Net Core SDK 2.1.503(x64) Microsoft Web Deploy 4.0

After going through all the articles available and tweaking and changing the app was finally worked but later it stopped working and giving the above error. My Startup.cs

public class Startup 
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;

        });

        services.Configure<DataProtectionTokenProviderOptions>(o =>
        {
            o.Name = "Default";
            o.TokenLifespan = TimeSpan.FromHours(1);
        });


        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
        mysqloptions => {
            mysqloptions.ServerVersion(new Version(8, 0, 13), ServerType.MySql);
        }));

        services.AddTransient<IProductRepository, EFProductRepository>();

        services.AddScoped<Cart>(sp => SessionCart.GetCart(sp));
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddIdentity<ApplicationUser, IdentityRole>(
            options =>
            {
                options.Stores.MaxLengthForKeys = 128;
                options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
                options.SignIn.RequireConfirmedEmail = false;
                options.Password.RequireDigit = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
            }

            )
              .AddEntityFrameworkStores<ApplicationDbContext>()
              .AddRoleManager<RoleManager<IdentityRole>>()
              .AddRoles<IdentityRole>()
           //.AddDefaultUI();
           .AddDefaultTokenProviders();

        //Authentication







        services.AddDbContext<MainContext>(options =>
      options.UseMySql(Configuration.GetConnectionString("ModelConnectionString"),

       mysqloptions => {
           mysqloptions.ServerVersion(new Version(8, 0, 13), ServerType.MySql);
           mysqloptions.MigrationsAssembly("GasStationApp");
       }));






        services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, MyUserClaimsPrincipalFactory>();


        services.AddMvc().AddNToastNotifyToastr(new ToastrOptions()
        {
            ProgressBar = false,
            PositionClass = ToastPositions.TopFullWidth

        }
        );



        services.Configure<IISOptions>(options => {
            options.AutomaticAuthentication = false;
            options.ForwardClientCertificate = false;

});

My Program.cs

public class Program
{
    public static int Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.RollingFile("logs/log-{Date}.txt")
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            BuildWebHost(args).Run();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }



    }



    public static IWebHost BuildWebHost(string[] args) =>
      WebHost.CreateDefaultBuilder(args)
        .UseKestrel()
        .ConfigureAppConfiguration((builderContext, config) =>
        {
            config.AddJsonFile("appsettings.json", optional: false);
        })
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
      .UseStartup<Startup>()
          .UseSerilog() // <-- Add this line
          .Build();

}

The app works fine in VS2017 but does not work when deployed to IIS in Windows 10 Please help me resolve this issue. Any advice would be helpful. Thanks in advance.

This kinda weird, the deployed files has three appsettings.json, appsettings.development.json, appsettings.production.json. I failed to look into this because, I thought the default appsettings.json file should have the original configuration but it turned out that the appsettings.json and appsettings.development.json in the deployed folder has only the default settings which were available when you create a web app project in VS 2017. appsettings.production.json file has the original configuration. Solution. Copied the appsettings.production.json file and renamed it to appsettings.json and the web app works fine now. 在此处输入图片说明

The files are appsettings.json and appsettings.{environment}.json . ASP.NET Core relies on an environment variable ( ASPNETCORE_ENVIRONMENT ) to determine which config(s) to load. By default, this is set to Development in Visual Studio, which then of course causes appsettings.Development.json to be utilized. When you publish your app, you should then set the ASPNETCORE_ENVIRONMENT environment variable on the destination to Production , which would then cause appsettings.Production.json to be utilized. (I do not remember if casing matters, though it might, especially with case-sensitive file systems like those utilized by Linux and Mac OS. It's best to just ensure that the file is named appsettings.Production.json , just in case.)

Additionally, the environment-specific JSON file overrides the inspecific one. In other words, appsettings.json is read in first, and then appsettings.{environment}.json is read in. Anything in appsettings.json set also in the environment-specific version will be overridden by that value in the environment-specific version.

In short, the pattern should be this. Any config not specific to a particular environment should go into appsettings.json . Any environment-specific config should go into the respective environment-specific config files. I've found it to be good practice to put placeholders for environment-specific and secret config values in appsettings.json as well. For example:

 "ConnectionStrings": {
     "DefaultConnection": "[CONNECTION STRING]"
 }

Due to the way that config layers upon itself, and since appsettings.json is the first thing to be loaded in, you can provide the actual value in any other form of config (environment-specific JSON, environment variables, user secrets, Azure Key Vault, etc.). This then documents all your app's config in one place, with clear indication of what needs to actually be provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM