0

I'm using EC2 to deploy my ASP.net Core MVC web application on IIS. I've published a medium sized project and the browser display the following message "HTTP Error 503. The service is unavailable. " I've published another new project "Empty" with the same setting as the previous project and the publishing succeeded i tried many solution such as :

  • making sure that the application poll is not stopped
  • turn the loading user profile to false
  • check the logs files for the following paths

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

i didn't understand the error and I'm hoping for some help

BTW I've published the same web application previously on Azure and it is up and running. Now I'm trying to republish using IIS is the previous publishing may cause this problem ?

startup.cs file

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 file

{
  "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": "*"
}
Amani
  • 63
  • 1
  • 7
  • You can use FRT to view detailed error messages: https://learn.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis – Ding Peng Mar 19 '21 at 05:04
  • There are differences in how you have deployed the empty application and how you have deployed the real application. It might be that you are not listening on the default ports. Compare the startup.cs and appsettings.json files in the two projects and see if their are any differences. If they are exactly the same, make sure that the methods you used to deploy the two apps were identical. – GlennSills Mar 19 '21 at 14:02
  • @GlennSills it is surly different but i cant pin point the problem – Amani Mar 20 '21 at 22:24
  • If possible, post your startup.cs and appsettings.json so people can help you. – GlennSills Mar 21 '21 at 14:40
  • @GlennSills I did thank you – Amani Mar 23 '21 at 02:14
  • Did you use FRT to troubleshoot this issue? – Ding Peng Mar 25 '21 at 07:09

1 Answers1

1

It turns out that the problem is that i didn't have a valid connection string in my Appsetting.json

My startup.cs file is invoking dbInitializer which requires a valid database connection i struggled finding the correct form for the connection string, this is the form if anyone needs it:

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

ps: my database is hosted by AWS

Thank you all

Amani
  • 63
  • 1
  • 7