IIS HTTP 错误 503。服务不可用

Posted

技术标签:

【中文标题】IIS HTTP 错误 503。服务不可用【英文标题】:IIS HTTP Error 503. The service is unavailable 【发布时间】:2021-06-16 09:49:28 【问题描述】:

我正在使用 EC2 在 IIS 上部署我的 ASP.net Core MVC Web 应用程序。我发布了一个中型项目,浏览器显示以下消息“HTTP 错误 503。服务不可用。 " 我发布了另一个新项目“Empty”,设置与上一个项目相同,并且发布成功 我尝试了很多解决方案,例如:

确保应用程序轮询没有停止 将正在加载的用户配置文件设为 false 检查以下路径的日志文件

C:\Windows\System32\LogFiles\HTTPERR

2021-03-18 22:12:09 ***.**.**.** 3380 ***.**.**.** 80 HTTP/1.1 GET / - 503 4 AppOffline TestApplication

C:\inetpub\logs\LogFiles\W3SVC4

2021-03-18 20:57:27 ::1 GET / - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - localhost 503 0 1115 4833 264 24

2021-03-18 20:57:27 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - localhost 503 0 1115 4856 206 6

我不明白这个错误,我希望得到一些帮助

顺便说一句 我之前在 Azure 上发布了相同的 Web 应用程序,它已启动并正在运行。现在我正在尝试使用 IIS 重新发布是以前的发布可能会导致这个问题吗?

startup.cs 文件

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Qessa.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Qessa.Models;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Hangfire;
using Qessa.Services;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;


namespace Qessa

    public class Startup
    
        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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.ConfigureApplicationCookie(options =>
            
                options.Cookie.Name = ".ExpirationCookie";
                options.Cookie.IsEssential = true;
                options.Cookie.HttpOnly = true;
                //options.LoginPath = "/Identity/Pages/Account/Login";
                options.AccessDeniedPath = "/Identity/Pages/Account/AccessDenied"; 
                options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                options.SlidingExpiration = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Events = new CookieAuthenticationEvents
                
                    OnValidatePrincipal = ValidateAsync.ValidatingAsync
                ;
            )
            .Configure<SecurityStampValidatorOptions>(options =>
            
                options.ValidationInterval = TimeSpan.FromMinutes(0); //1 minute for testing, This time should be zero, so once the user account turned to expired it will waits for this time then force logout.
            );

            services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(
                  Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>(options => 
                options.SignIn.RequireConfirmedAccount = false;
                //options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
            )
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders(); 

            services.AddIdentityCore<ApplicationUser>()
                .AddRoles<IdentityRole>()
                .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI();

            services.AddSingleton<IEmailSender, EmailSender>();
            services.Configure<EmailOptions>(Configuration);

            services.AddHangfire(config => config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
            services.AddHangfireServer();


            services.AddControllersWithViews(); 
            services.AddRazorPages().AddRazorRuntimeCompilation();

            services.AddScoped<IDbInitializer, DbInitializer>();

            services.AddScoped<IExpirationJob, ExpirationJob>();
            services.AddScoped<IReminderJob, EmailReminder>();

            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
        

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IWebHostEnvironment env,
            IRecurringJobManager recurringJobManager,
            IServiceProvider serviceProvider,
            IDbInitializer dbInitializer)
        
            if (env.IsDevelopment())
            
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            
            else
            
                app.UseExceptionHandler("/Home/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();
            
            dbInitializer.Initialize();
            app.UseHttpsRedirection();
            app.UseStaticFiles();


            app.UseHangfireDashboard();
            app.UseHangfireDashboard("/hangfire", new DashboardOptions()
            
                Authorization = new[]  new CustomAuthorizeFilter() 
            );


            app.UseRouting();


            app.UseAuthentication();
            app.UseAuthorization();


            app.UseCookiePolicy();

            recurringJobManager.AddOrUpdate(
               "End Users Subscription",
               () => serviceProvider.GetService<IExpirationJob>().SetExpired(),
               Cron.Daily
               );

            recurringJobManager.AddOrUpdate(
               "Send End of Subscription Reminder",
               () => serviceProvider.GetService<IReminderJob>().SendReminder(),
               Cron.Daily
               );

            app.UseEndpoints(endpoints =>
            
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "controller=Home/action=Index/id?");
                endpoints.MapRazorPages();
            );
        
    

appsetting.json 文件


  "ConnectionStrings": 
    "DefaultConnection": "Server=LAPTOP-CPJTBQI1;Database=QessaDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  ,
  "Logging": 
    "LogLevel": 
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    ,

    "name": "asp.net",
    "private": true,
    "dependencies": 
      "bootstrap": "3.3.7",
      "jquery": "3.1.1",
      "jquery-validation": "1.16.0",
      "jquery-validation-unobtrusive": "3.2.6",
      "requirejs": "2.3.3",
      "chart.js": "2.5.0"
    

  ,
  "SendGridKey": "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",
  "AllowedHosts": "*"

【问题讨论】:

可以使用FRT查看详细错误信息:docs.microsoft.com/en-us/iis/troubleshoot/… 部署空应用程序的方式与部署真实应用程序的方式存在差异。可能是您没有在默认端口上侦听。比较两个项目中的 startup.cs 和 appsettings.json 文件,看看它们是否有区别。如果它们完全相同,请确保您用于部署这两个应用程序的方法相同。 @GlennSills 它完全不同,但我无法指出问题 如果可能,请发布您的 startup.cs 和 appsettings.json,以便人们可以帮助您。 @GlennSills 谢谢你 【参考方案1】:

原来问题在于我的 Appsetting.json 中没有有效的连接字符串

我的 startup.cs 文件正在调用 dbInitializer,它需要一个有效的数据库连接

    "DefaultConnection": "Server=data.*************.rds.amazonaws.com;database=data;uid=*****;pwd=*****;"

ps:我的数据库由 AWS 托管

谢谢大家

【讨论】:

以上是关于IIS HTTP 错误 503。服务不可用的主要内容,如果未能解决你的问题,请参考以下文章

HTTP 错误 503。该服务在 IIS 中不可用

HTTP 错误 503。尝试运行本地主机时服务不可用

Http错误503服务不可用

IIS 7 服务不可用 503 错误

HTTP 错误 503。当端口 80 已经空闲时服务不可用

503 服务不可用没有被任何 IIS 错误页面或 ASP.net 错误页面处理