Advertisement
saigkill0

Startup

Dec 8th, 2022
935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.00 KB | Fixit | 0 0
  1. namespace MannsBlog
  2. {
  3.     /// <summary>
  4.     /// Startup Class.
  5.     /// </summary>
  6.     public class Startup
  7.     {
  8.         /// <summary>
  9.         /// The cors policy name.
  10.         /// </summary>
  11.         public const string CorsPolicyName = "_saigkills_cors";
  12.  
  13.         /// <summary>
  14.         /// Initializes a new instance of the <see cref="Startup"/> class.
  15.         /// </summary>
  16.         /// <param name="configuration">The configuration.</param>
  17.         /// <param name="environment">The environment.</param>
  18.         public Startup(IConfiguration configuration, IHostEnvironment environment, ILoggerFactory loggerFactory, IMailService mailService, IOptions<AppSettings> settings, IHttpContextAccessor contextAccessor)
  19.         {
  20.             this.ConfigRoot = configuration;
  21.             this.Env = environment;
  22.             this.LoggerFactory = loggerFactory;
  23.             this.MailService = mailService;
  24.             this.Settings = settings;
  25.             this.ContextAccessor = contextAccessor;
  26.         }
  27.  
  28.         /// <summary>
  29.         /// Gets the configuration root.
  30.         /// </summary>
  31.         /// <value>
  32.         /// The configuration root.
  33.         /// </value>
  34.         public IConfiguration ConfigRoot
  35.         {
  36.             get;
  37.         }
  38.  
  39.         /// <summary>
  40.         /// Gets the env.
  41.         /// </summary>
  42.         /// <value>
  43.         /// The env.
  44.         /// </value>
  45.         public IHostEnvironment Env
  46.         {
  47.             get;
  48.         }
  49.  
  50.         public ILoggerFactory LoggerFactory
  51.         {
  52.             get;
  53.         }
  54.  
  55.         public IMailService MailService
  56.         {
  57.             get;
  58.         }
  59.  
  60.         public IOptions<AppSettings> Settings
  61.         {
  62.             get;
  63.         }
  64.  
  65.         public IHttpContextAccessor ContextAccessor
  66.         {
  67.             get;
  68.         }
  69.  
  70.         /// <summary>
  71.         /// Configures the services.
  72.         /// </summary>
  73.         /// <param name="services">The services.</param>
  74.         public void ConfigureServices(IServiceCollection services)
  75.         {
  76.             // Add services to the container.
  77.             services.Configure<AppSettings>(this.ConfigRoot);
  78.  
  79.             if (this.Env.IsDevelopment() && this.ConfigRoot.GetValue<bool>("MailService:TestInDev") == false)
  80.             {
  81.                 services.AddTransient<IMailService, LoggingMailService>();
  82.             }
  83.             else
  84.             {
  85.                 services.AddTransient<IMailService, SendgridMailService>();
  86.             }
  87.  
  88.             services.AddTransient<GoogleCaptchaService>();
  89.  
  90.             services.AddIdentity<MannsUser, IdentityRole>().AddEntityFrameworkStores<MannsContext>();
  91.  
  92.             if (this.ConfigRoot.GetValue<bool>("MannsDb:TestData"))
  93.             {
  94.                 services.AddScoped<IMannsRepository, MemoryRepository>();
  95.             }
  96.             else
  97.             {
  98.                 services.AddScoped<IMannsRepository, MannsRepository>();
  99.             }
  100.  
  101.             services.AddCors(setup =>
  102.             {
  103.                 setup.AddPolicy(CorsPolicyName, cfg =>
  104.                 {
  105.                     if (this.Env.IsDevelopment())
  106.                     {
  107.                         cfg.AllowAnyMethod();
  108.                         cfg.AllowAnyOrigin();
  109.                         cfg.AllowAnyHeader();
  110.                     }
  111.                     else
  112.                     {
  113.                         cfg.WithMethods("POST");
  114.                         cfg.WithOrigins(
  115.                             "https://saschamanns.de",
  116.                             "http://saschamanns.de");
  117.                         cfg.AllowAnyHeader();
  118.                     }
  119.                 });
  120.             });
  121.  
  122.             services.ConfigureHealthChecks(this.ConfigRoot);
  123.  
  124.             services.AddTransient<SeedData>();
  125.             services.AddScoped<AdService>();
  126.  
  127.             // Non EF data.
  128.             services.AddScoped<CalendarProvider>();
  129.             services.AddScoped<PublicationProvider>();
  130.             services.AddScoped<TalksProvider>();
  131.             services.AddScoped<VideosProvider>();
  132.             services.AddScoped<JobsProvider>();
  133.             services.AddScoped<TestimonialsProvider>();
  134.             services.AddScoped<CertsProvider>();
  135.             services.AddScoped<ProjectsProvider>();
  136.  
  137.             if ((this.Env.IsDevelopment() && this.ConfigRoot.GetValue<bool>("BlobStorage:TestInDev") == false) || this.ConfigRoot.GetValue<string>("BlobStorage:Account") == "FOO")
  138.             {
  139.                 services.AddTransient<IAzureImageStorageService, FakeAzureImageService>();
  140.             }
  141.             else
  142.             {
  143.                 services.AddAzureImageStorageService(this.ConfigRoot.GetValue<string>("BlobStorage:Account"), this.ConfigRoot.GetValue<string>("BlobStorage:Key"), this.ConfigRoot.GetValue<string>("BlobStorage:StorageUrl"));
  144.             }
  145.  
  146.             services.AddMetaWeblog<MannsWeblogProvider>();
  147.             services.AddMemoryCache(opt => opt.ExpirationScanFrequency = TimeSpan.FromMinutes(5));
  148.  
  149.             // Add MVC to the container
  150.             services.AddRazorPages();
  151.             services.AddServerSideBlazor();
  152.             services.AddMvc(); // TODO: Add Localisation
  153.         }
  154.  
  155.         /// <summary>
  156.         /// Configures the specified application.
  157.         /// </summary>
  158.         /// <param name="app">The application.</param>
  159.         /// <param name="env">The env.</param>
  160.         public void Configure(WebApplication app, IWebHostEnvironment env)
  161.         {
  162.             // Configure the HTTP request pipeline.
  163.             if (!app.Environment.IsDevelopment())
  164.             {
  165.                 // Early so we can catch the StatusCode error.
  166.                 app.UseStatusCodePagesWithReExecute("/Error/{0}");
  167.                 app.UseExceptionHandler("/Exception");
  168.  
  169.                 // Support for logging to email.
  170.                 this.LoggerFactory.AddEmail(this.MailService, this.ContextAccessor, LogLevel.Critical);
  171.  
  172.                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  173.                 app.UseHsts();
  174.             }
  175.             else
  176.             {
  177.                 app.UseDeveloperExceptionPage();
  178.                 app.UseBrowserLink();
  179.             }
  180.  
  181.             app.UseHttpsRedirection();
  182.  
  183.             // Support Metaweblog API.
  184.             app.UseMetaWeblog("/livewriter");
  185.  
  186.             // Rewrite old Urls.
  187.             app.UseUrlRewriter();
  188.  
  189.             app.UseStaticFiles();
  190.  
  191.             // Email Uncaught Exceptions
  192.             if (this.Settings.Value.Exceptions.TestEmailExceptions || !app.Environment.IsDevelopment())
  193.             {
  194.                 app.UseMiddleware<EmailExceptionMiddleware>();
  195.             }
  196.  
  197.             app.UseRouting();
  198.             app.UseCors();
  199.             app.UseAuthentication();
  200.             app.UseAuthorization();
  201.  
  202.             app.MapControllers();
  203.             app.MapBlazorHub();
  204.             app.MapFallbackToPage("/_Host");
  205.             app.MapHealthChecks("/health", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
  206.             {
  207.                 ResultStatusCodes =
  208.                 {
  209.                     [HealthStatus.Healthy] = StatusCodes.Status200OK,
  210.                     [HealthStatus.Degraded] = StatusCodes.Status200OK,
  211.                     [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
  212.                 },
  213.                 Predicate = _ => true,
  214.                 ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
  215.             });
  216.  
  217.             // Initialize the database
  218.             var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
  219.             using (var scope = scopeFactory.CreateScope())
  220.             {
  221.                 var ctx = scope.ServiceProvider.GetRequiredService<MannsContext>();
  222.  
  223.                 if (ctx.Database.EnsureCreated())
  224.                 {
  225.                     SeedData.UserAsync();
  226.                     SeedData.StoriesAsync();
  227.                 }
  228.             }
  229.  
  230.             app.Run();
  231.         }
  232.     }
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement