【问题标题】:.net core 2.1 web app works in visual studio but does not work when deployed to IIS in windows 10.net core 2.1 Web 应用程序在 Visual Studio 中工作,但在 Windows 10 中部署到 IIS 时不起作用
【发布时间】:2019-02-28 11:45:46
【问题描述】:

我是 .net 核心开发的新手,我正在尝试在 Windows 10 中将 Web 应用程序 .net 核心 2.1 部署到 IIS。我已遵循所有步骤,包括创建应用程序池“无托管代码”并且一切正常。 2 天后它停止工作,然后我使用发布类型将我的项目重新部署到调试,在这里我在浏览器中显示了这个异常,这在日志文件中是相同的。

但是,相同的应用程序在 Visual Studio 中运行良好。我的机器安装了以下 .net 包。 .Net Core Runtme 2.1.7(x64) .Net Core 2.1.7 - Windows 服务器托管 .net 核心运行时 2.1.7(x86) .Net 核心 SDK 2.1.503 (x86) .Net Core SDK 2.1.503(x64) 微软网络部署 4.0

在浏览了所有可用的文章并调整和更改应用程序后,该应用程序终于工作了,但后来它停止工作并出现上述错误。 我的 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;

});

我的程序.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();

}

该应用程序在 VS2017 中运行良好,但在 Windows 10 中部署到 IIS 时无法运行 请帮我解决这个问题。任何意见将是有益的。提前致谢。

【问题讨论】:

    标签: c# iis asp.net-core web-deployment asp.net-core-2.1


    【解决方案1】:

    文件是appsettings.jsonappsettings.{environment}.json。 ASP.NET Core 依赖于环境变量 (ASPNETCORE_ENVIRONMENT) 来确定要加载哪些配置。默认情况下,这在 Visual Studio 中设置为 Development,这当然会导致使用 appsettings.Development.json。当您发布您的应用程序时,您应该将目标上的ASPNETCORE_ENVIRONMENT 环境变量设置为Production,这将导致appsettings.Production.json 被使用。 (我不记得大小写是否重要,尽管它可能,特别是对于区分大小写的文件系统,如 Linux 和 Mac OS 使用的文件系统。最好确保文件名为 appsettings.Production.json,以防万一。)

    此外,特定于环境的 JSON 文件会覆盖非特定的 JSON 文件。换句话说,首先读入appsettings.json,然后读入appsettings.{environment}.json。在特定环境版本中设置的appsettings.json 中的任何内容都将被特定环境版本中的该值覆盖。

    简而言之,模式应该是这样的。任何不特定于特定环境的配置都应该进入appsettings.json。任何特定于环境的配置都应进入相应的特定于环境的配置文件。我发现在appsettings.json 中放置环境特定和秘密配置值的占位符也是一种好习惯。例如:

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

    由于配置自身分层的方式,并且由于 appsettings.json 是首先加载的内容,因此您可以以任何其他形式的配置(特定于环境的 JSON、环境变量、用户机密)提供实际值、Azure Key Vault 等)。然后,这会将您应用的所有配置记录在一个位置,并明确指出实际需要提供的内容。

    【讨论】:

    • 感谢@ChrisPratt,提供的解释对我帮助很大。就我而言,正在使用 appsettings.json 而不是 appsettings.production.json。根据您的解释,应该使用 appsettings.production.json 。再次感谢。
    【解决方案2】:

    这有点奇怪,部署的文件有三个appsettings.json,appsettings.development.json,appsettings.production.json。我没有对此进行调查,因为我认为默认的 appsettings.json 文件应该具有原始配置,但事实证明部署文件夹中的 appsettings.json 和 appsettings.development.json 只有默认设置,当您在 VS 2017 中创建一个 web 应用项目。 appsettings.production.json 文件具有原始配置。 解决方案。 复制 appsettings.production.json 文件并将其重命名为 appsettings.json,网络应用程序现在可以正常工作了。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-30
    • 2019-01-06
    • 1970-01-01
    • 2015-08-16
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多