Migrate to .net5 from .netcore2.1

This commit is contained in:
2020-11-15 20:37:53 +00:00
parent 436d4cb1d1
commit abd71db13d
5 changed files with 215 additions and 90 deletions

2
.vscode/launch.json vendored
View File

@@ -10,7 +10,7 @@
"request": "launch", "request": "launch",
"preLaunchTask": "build", "preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path. // If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceRoot}/bin/Debug/netcoreapp2.1/pecklist.dll", "program": "${workspaceRoot}/bin/Debug/net5.0/pecklist.dll",
"args": [], "args": [],
"cwd": "${workspaceRoot}", "cwd": "${workspaceRoot}",
"stopAtEntry": false, "stopAtEntry": false,

View File

@@ -1,30 +1,47 @@
using System; using Microsoft.AspNetCore.Hosting;
using System.Collections.Generic; using Microsoft.Extensions.Hosting;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace GZTW.Pecklist namespace GZTW.Pecklist
{ {
public class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
BuildWebHost(args).Run(); CreateHostBuilder(args).Build().Run();
} }
public static IWebHost BuildWebHost(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args) Host.CreateDefaultBuilder(args)
.UseUrls("http://*:3000") .ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls("http://*:3000")
.CaptureStartupErrors(true) .CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true") .UseSetting("detailedErrors", "true")
.UseKestrel() .UseKestrel()
.UseContentRoot(System.IO.Directory.GetCurrentDirectory()) .UseContentRoot(System.IO.Directory.GetCurrentDirectory());
.UseStartup<Startup>() });
.Build();
} }
// public class Program
// {
// public static void Main(string[] args)
// {
// BuildWebHost(args).Run();
// }
// public static IWebHost BuildWebHost(string[] args) =>
// WebHost.CreateDefaultBuilder(args)
// .UseUrls("http://*:3000")
// .CaptureStartupErrors(true)
// .UseSetting("detailedErrors", "true")
// .UseKestrel()
// .UseContentRoot(System.IO.Directory.GetCurrentDirectory())
// .UseStartup<Startup>()
// .Build();
// }
} }

View File

@@ -1,121 +1,226 @@
using System; using Microsoft.AspNetCore.Builder;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using GZTW.Pecklist.Models; using GZTW.Pecklist.Models;
using GZTW.Pecklist.Util; using GZTW.Pecklist.Util;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication;
namespace GZTW.Pecklist namespace GZTW.Pecklist
{ {
public class Startup public class Startup
{ {
public Startup(IHostingEnvironment env) public Startup(IConfiguration configuration)
{ {
var builder = new ConfigurationBuilder() Configuration = configuration;
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
} }
public IConfigurationRoot Configuration { get; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers().AddNewtonsoftJson();
services.AddDbContext<PecklistContext>(options =>
{
options.UseSqlite(Configuration.GetConnectionString("thedb")).EnableSensitiveDataLogging(false);
services.AddDbContext<PecklistContext>(options => options.UseSqlite(Configuration.GetConnectionString("thedb"))); });
//Added this so that can access configuration from anywhere else
//See authcontroller for usage
services.AddSingleton<IConfiguration>(Configuration);
services.AddMvc();
//get the key from the appsettings.json file
var secretKey = Configuration.GetSection("JWT").GetValue<string>("secret"); var secretKey = Configuration.GetSection("JWT").GetValue<string>("secret");
var signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(secretKey)); var signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(secretKey));
services.AddAuthentication(options => services.AddAuthentication(options =>
{ {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => }).AddJwtBearer(options =>
{ {
// options.AutomaticAuthenticate = true; options.TokenValidationParameters = new TokenValidationParameters
// options.AutomaticChallenge = true; {
options.TokenValidationParameters = new TokenValidationParameters // Token signature will be verified using a private key.
{ ValidateIssuerSigningKey = true,
// Token signature will be verified using a private key. RequireSignedTokens = true,
ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey,
RequireSignedTokens = true, ValidateIssuer = true,
IssuerSigningKey = signingKey, ValidIssuer = "GZTW_Pecklist",
ValidateIssuer = true, ValidateAudience = false,
ValidIssuer = "GZTW_Pecklist",
ValidateAudience = false, //Note: these are all enabled in AyaNOva but were origionally disabled in rf
// ValidAudience = "https://yourapplication.example.com", // // Token will only be valid if not expired yet, with 5 minutes clock skew.
// ValidateLifetime = true,
// RequireExpirationTime = true,
// ClockSkew = new TimeSpan(0, 5, 0),
};
});
// Token will only be valid if not expired yet, with 5 minutes clock skew.
// ValidateLifetime = true,
// RequireExpirationTime = true,
// ClockSkew = new TimeSpan(0, 5, 0),
};
});
} }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, PecklistContext dbContext) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PecklistContext dbContext)
{ {
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseDefaultFiles(); app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions app.UseStaticFiles(new StaticFileOptions
{ {
OnPrepareResponse = context => OnPrepareResponse = context =>
{ {
if (context.File.Name == "index.html" || context.File.Name == "sw.js" ) if (context.File.Name == "default.htm")
{ {
context.Context.Response.Headers.Add("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"); context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
// context.Context.Response.Headers.Add("Expires", "-1"); context.Context.Response.Headers.Add("Expires", "-1");
} }
} }
}); });
app.UseAuthentication(); app.UseAuthentication();
app.UseMvc();
//Check schema //Check schema
Schema.CheckAndUpdate(dbContext); Schema.CheckAndUpdate(dbContext);
// app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//server ready
System.Diagnostics.Debug.WriteLine("BOOT COMPLETED - OPEN");
} }
} }
} }
// using Microsoft.AspNetCore.Builder;
// using Microsoft.IdentityModel.Tokens;
// using Microsoft.AspNetCore.HttpOverrides;
// using Microsoft.Extensions.Configuration;
// using Microsoft.Extensions.DependencyInjection;
// using Microsoft.Extensions.Logging;
// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.Hosting;
// using Microsoft.AspNetCore.Authentication.JwtBearer;
// using GZTW.Pecklist.Models;
// using GZTW.Pecklist.Util;
// namespace GZTW.Pecklist
// {
// public class Startup
// {
// public Startup(Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
// {
// var builder = new ConfigurationBuilder()
// .SetBasePath(env.ContentRootPath)
// .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
// .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// .AddEnvironmentVariables();
// Configuration = builder.Build();
// }
// public IConfigurationRoot Configuration { get; }
// // This method gets called by the runtime. Use this method to add services to the container.
// public void ConfigureServices(IServiceCollection services)
// {
// services.AddDbContext<PecklistContext>(options => options.UseSqlite(Configuration.GetConnectionString("thedb")));
// //Added this so that can access configuration from anywhere else
// //See authcontroller for usage
// services.AddSingleton<IConfiguration>(Configuration);
// services.AddMvc();
// //get the key from the appsettings.json file
// var secretKey = Configuration.GetSection("JWT").GetValue<string>("secret");
// var signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(secretKey));
// services.AddAuthentication(options =>
// {
// options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
// }).AddJwtBearer(options =>
// {
// // options.AutomaticAuthenticate = true;
// // options.AutomaticChallenge = true;
// options.TokenValidationParameters = new TokenValidationParameters
// {
// // Token signature will be verified using a private key.
// ValidateIssuerSigningKey = true,
// RequireSignedTokens = true,
// IssuerSigningKey = signingKey,
// ValidateIssuer = true,
// ValidIssuer = "GZTW_Pecklist",
// ValidateAudience = false,
// // ValidAudience = "https://yourapplication.example.com",
// // Token will only be valid if not expired yet, with 5 minutes clock skew.
// // ValidateLifetime = true,
// // RequireExpirationTime = true,
// // ClockSkew = new TimeSpan(0, 5, 0),
// };
// });
// }
// public void Configure(IApplicationBuilder app, IHostEnvironment env, PecklistContext dbContext)
// {//ILoggerFactory loggerFactory,
// if (env.IsDevelopment())
// {
// app.UseDeveloperExceptionPage();
// }
// var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
// // loggerFactory.AddConsole(Configuration.GetSection("Logging"));
// // loggerFactory.AddDebug();
// app.UseForwardedHeaders(new ForwardedHeadersOptions
// {
// ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
// });
// app.UseDefaultFiles();
// app.UseStaticFiles(new StaticFileOptions
// {
// OnPrepareResponse = context =>
// {
// if (context.File.Name == "index.html" || context.File.Name == "sw.js")
// {
// context.Context.Response.Headers.Add("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0");
// // context.Context.Response.Headers.Add("Expires", "-1");
// }
// }
// });
// app.UseAuthentication();
// //app.UseMvc();
// //Check schema
// Schema.CheckAndUpdate(dbContext);
// }
// }
// }

Binary file not shown.

View File

@@ -1,17 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>net5.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Folder Include="wwwroot\" /> <Folder Include="wwwroot\" />
<Content Remove="wwwroot\js\templates\*.handlebars" /> <Content Remove="wwwroot\js\templates\*.handlebars" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0" /> <!-- <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0" /> -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
<!-- <PackageReference Include="Newtonsoft.Json" Version="10.0.3" /> --> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" />
<PackageReference Include="jose-jwt" Version="2.4.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.0" />
<PackageReference Include="jose-jwt" Version="2.6.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
</ItemGroup> </ItemGroup>