|
1 |
| -using Microsoft.AspNetCore; |
2 |
| -using Microsoft.AspNetCore.Hosting; |
3 |
| -using Microsoft.AspNetCore.Server.HttpSys; |
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using Newtonsoft.Json.Serialization; |
| 4 | +using System.Text; |
| 5 | +using System.Text.Encodings.Web; |
| 6 | +using AlbumViewerAspNetCore; |
4 | 7 | using Microsoft.Extensions.Configuration;
|
| 8 | +using AlbumViewerBusiness; |
| 9 | +using AlbumViewerBusiness.Configuration; |
| 10 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 11 | +using Microsoft.AspNetCore.Builder; |
| 12 | +using Microsoft.AspNetCore.Diagnostics; |
| 13 | +using Microsoft.AspNetCore.Http; |
| 14 | +using Microsoft.EntityFrameworkCore; |
| 15 | +using Microsoft.Extensions.DependencyInjection; |
| 16 | +using Microsoft.Extensions.Hosting; |
| 17 | +using Microsoft.IdentityModel.Tokens; |
5 | 18 |
|
6 |
| -namespace AlbumViewerNetCore |
| 19 | + |
| 20 | +var builder = WebApplication.CreateBuilder(args); |
| 21 | +var services = builder.Services; |
| 22 | +var configuration = builder.Configuration; |
| 23 | + |
| 24 | +var host = builder.Host; |
| 25 | +var webHost = builder.WebHost; |
| 26 | +var environment = builder.Environment; |
| 27 | + |
| 28 | + |
| 29 | +services.AddDbContext<AlbumViewerContext>(builder => |
7 | 30 | {
|
8 |
| - public class Program |
| 31 | + string useSqLite = configuration["Data:useSqLite"]; |
| 32 | + if (useSqLite != "true") |
9 | 33 | {
|
10 |
| - public static void Main(string[] args) |
11 |
| - { |
12 |
| - var builder = CreateWebHostBuilder(args); |
13 |
| - builder.Build().Run(); |
14 |
| - } |
15 |
| - public static IWebHostBuilder CreateWebHostBuilder(string[] args) |
| 34 | + var connStr = configuration["Data:SqlServerConnectionString"]; |
| 35 | + builder.UseSqlServer(connStr, opt => opt.EnableRetryOnFailure()); |
| 36 | + } |
| 37 | + else |
| 38 | + { |
| 39 | + // Note this path has to have full access for the Web user in order |
| 40 | + // to create the DB and write to it. |
| 41 | + var connStr = "Data Source=" + |
| 42 | + Path.Combine(environment.ContentRootPath, "AlbumViewerData.sqlite"); |
| 43 | + builder.UseSqlite(connStr); |
| 44 | + } |
| 45 | +}); |
| 46 | + |
| 47 | + |
| 48 | +var config = new ApplicationConfiguration(); |
| 49 | +configuration.Bind("Application", config); |
| 50 | +services.AddSingleton(config); |
| 51 | + |
| 52 | +App.Configuration = config; |
| 53 | + |
| 54 | +// Also make top level configuration available (for EF configuration and access to connection string) |
| 55 | +services.AddSingleton<IConfigurationRoot>(configuration); |
| 56 | +services.AddSingleton<IConfiguration>(configuration); |
| 57 | + |
| 58 | +// Cors policy is added to controllers via [EnableCors("CorsPolicy")] |
| 59 | +// or .UseCors("CorsPolicy") globally |
| 60 | +services.AddCors(options => |
| 61 | +{ |
| 62 | + options.AddPolicy("CorsPolicy", |
| 63 | + builder => builder |
| 64 | + // required if AllowCredentials is set also |
| 65 | + .SetIsOriginAllowed(s => true) |
| 66 | + //.AllowAnyOrigin() |
| 67 | + .AllowAnyMethod() // doesn't work for DELETE! |
| 68 | + .WithMethods("DELETE") |
| 69 | + .AllowAnyHeader() |
| 70 | + .AllowCredentials() |
| 71 | + ); |
| 72 | +}); |
| 73 | + |
| 74 | +services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 75 | + .AddJwtBearer(options => |
| 76 | + { |
| 77 | + options.TokenValidationParameters = new TokenValidationParameters |
16 | 78 | {
|
| 79 | + ValidateIssuer = true, |
| 80 | + ValidIssuer = config.JwtToken.Issuer, |
| 81 | + ValidateAudience = true, |
| 82 | + ValidAudience = config.JwtToken.Audience, |
| 83 | + ValidateIssuerSigningKey = true, |
| 84 | + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtToken.SigningKey)) |
| 85 | + }; |
| 86 | + |
| 87 | + }); |
17 | 88 |
|
18 |
| - var builder = WebHost.CreateDefaultBuilder(args) |
19 |
| - .UseStartup<Startup>(); |
20 |
| - //.UseIIS() |
21 |
| - //.UseHttpSys(options => |
22 |
| - //{ |
23 |
| - // options.Authentication.Schemes = AuthenticationSchemes.None; |
24 |
| - // options.Authentication.AllowAnonymous = true; |
25 |
| - // options.MaxConnections = 100; |
26 |
| - // options.MaxRequestBodySize = 30000000; |
27 |
| - // options.UrlPrefixes.Add("http://localhost:5002"); |
28 |
| - //}) |
29 |
| - |
30 |
| - |
31 |
| - return builder; |
| 89 | +// Instance injection |
| 90 | +services.AddScoped<AlbumRepository>(); |
| 91 | +services.AddScoped<ArtistRepository>(); |
| 92 | +services.AddScoped<AccountRepository>(); |
32 | 93 |
|
| 94 | +// Per request injections |
| 95 | +services.AddScoped<ApiExceptionFilter>(); |
| 96 | + |
| 97 | +services.AddControllers() |
| 98 | + // Use classic JSON |
| 99 | + .AddNewtonsoftJson(opt => |
| 100 | + { |
| 101 | + var resolver = opt.SerializerSettings.ContractResolver; |
| 102 | + if (resolver != null) |
| 103 | + { |
| 104 | + var res = resolver as DefaultContractResolver; |
| 105 | + res.NamingStrategy = null; |
33 | 106 | }
|
34 | 107 |
|
| 108 | + if (environment.IsDevelopment()) |
| 109 | + opt.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; |
| 110 | + }); |
35 | 111 |
|
36 |
| - } |
| 112 | +// |
| 113 | +// *** BUILD THE APP |
| 114 | +// |
| 115 | +var app = builder.Build(); |
| 116 | + |
| 117 | + |
| 118 | +// Get any injected items |
| 119 | +var albumContext = app.Services.CreateScope().ServiceProvider.GetService<AlbumViewerContext>(); |
| 120 | + |
| 121 | + |
| 122 | + |
| 123 | +//Log.Logger = new LoggerConfiguration() |
| 124 | +// .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log") |
| 125 | +// .CreateLogger(); |
| 126 | + |
| 127 | +//loggerFactory |
| 128 | +// .AddSerilog(); |
| 129 | + |
| 130 | + |
| 131 | +if (environment.IsDevelopment()) |
| 132 | +{ |
| 133 | + app.UseDeveloperExceptionPage(); |
| 134 | + |
| 135 | + //app.UseDatabaseErrorPage(); |
| 136 | +} |
| 137 | +else |
| 138 | +{ |
| 139 | + app.UseExceptionHandler(errorApp => |
| 140 | + |
| 141 | + // Application level exception handler here - this is just a place holder |
| 142 | + errorApp.Run(async (context) => |
| 143 | + { |
| 144 | + context.Response.StatusCode = 500; |
| 145 | + context.Response.ContentType = "text/html"; |
| 146 | + await context.Response.WriteAsync("<html><body>\r\n"); |
| 147 | + await context.Response.WriteAsync( |
| 148 | + "We're sorry, we encountered an un-expected issue with your application.<br>\r\n"); |
| 149 | + |
| 150 | + // Capture the exception |
| 151 | + var error = context.Features.Get<IExceptionHandlerFeature>(); |
| 152 | + if (error != null) |
| 153 | + { |
| 154 | + // This error would not normally be exposed to the client |
| 155 | + await |
| 156 | + context.Response.WriteAsync("<br>Error: " + |
| 157 | + HtmlEncoder.Default.Encode(error.Error.Message) + |
| 158 | + "<br>\r\n"); |
| 159 | + } |
| 160 | + await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n"); |
| 161 | + await context.Response.WriteAsync("</body></html>\r\n"); |
| 162 | + await context.Response.WriteAsync(new string(' ', 512)); // Padding for IE |
| 163 | + })); |
37 | 164 | }
|
| 165 | + |
| 166 | +//app.UseHttpsRedirection(); |
| 167 | + |
| 168 | + |
| 169 | +app.UseStatusCodePages(); |
| 170 | +app.UseDefaultFiles(); // so index.html is not required |
| 171 | +app.UseStaticFiles(); |
| 172 | + |
| 173 | +app.UseRouting(); |
| 174 | + |
| 175 | +app.UseCors("CorsPolicy"); |
| 176 | + |
| 177 | +app.UseAuthentication(); |
| 178 | +app.UseAuthorization(); |
| 179 | + |
| 180 | +// don't use the new simpler syntax as it doesn't terminate |
| 181 | +// and always fires the catch-all route below |
| 182 | +// if you don't have a catch-all route then this syntax is preferrable |
| 183 | +// app.MapControllers(); |
| 184 | + |
| 185 | + |
| 186 | +// endpoint handler terminates and allows for catch-all middleware below |
| 187 | +app.UseEndpoints(app => |
| 188 | +{ |
| 189 | + app.MapControllers(); |
| 190 | +}); |
| 191 | + |
| 192 | +// catch-all handler for HTML5 client routes - serve index.html |
| 193 | +app.Run(async context => |
| 194 | +{ |
| 195 | + var path = context.Request.Path.Value; |
| 196 | + |
| 197 | + // Make sure Angular output was created in wwwroot |
| 198 | + // Running Angular in dev mode nukes output folder! |
| 199 | + // so it could be missing. |
| 200 | + if (environment.WebRootPath == null) |
| 201 | + throw new InvalidOperationException("wwwroot folder doesn't exist. Please recompile your Angular Project before accessing index.html. API calls will work fine."); |
| 202 | + |
| 203 | + context.Response.ContentType = "text/html"; |
| 204 | + await context.Response.SendFileAsync(Path.Combine(environment.WebRootPath, "index.html")); |
| 205 | +}); |
| 206 | + |
| 207 | +// Initialize Database if it doesn't exist |
| 208 | +AlbumViewerDataImporter.EnsureAlbumData(albumContext, Path.Combine(environment.ContentRootPath, "albums.js")); |
| 209 | + |
| 210 | +Console.ForegroundColor = ConsoleColor.DarkYellow; |
| 211 | +Console.WriteLine($@"---------------- |
| 212 | +AlbumViewer Core |
| 213 | +----------------"); |
| 214 | +Console.ResetColor(); |
| 215 | + |
| 216 | +Console.WriteLine("\r\nPlatform: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription); |
| 217 | +Console.WriteLine(".NET Version: " + System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); |
| 218 | +Console.WriteLine("Hosting Environment: " + environment.EnvironmentName); |
| 219 | +string useSqLite = configuration["Data:useSqLite"]; |
| 220 | +Console.WriteLine(useSqLite == "true" ? "SqLite" : "Sql Server"); |
| 221 | + |
| 222 | + |
| 223 | + |
| 224 | + |
| 225 | +app.Run(); |
0 commit comments