// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { #region 顯示所讀取的 Configuration 內容值 bool showImportanceConfigurationInforation = Convert.ToBoolean(Configuration["ShowImportanceConfigurationInforation"]); if (showImportanceConfigurationInforation) { AllConfigurationHelper.Show(Configuration); } #endregion #region Blazor & Razor Page 用到服務 services.AddRazorPages(); #region Blazor Server 註冊服務,正式部署下,是否要顯示明確的例外異常資訊 bool emergenceDebugStatus = Convert.ToBoolean(Configuration["EmergenceDebug"]); if (emergenceDebugStatus == true) { Console.WriteLine($"啟用正式部署可以顯示錯誤詳細資訊"); services.AddServerSideBlazor() .AddCircuitOptions(e => { e.DetailedErrors = true; }); } else { services.AddServerSideBlazor(); } #endregion #endregion #region Syncfusion 元件與多國語言服務 // Localization https://github.com/syncfusion/blazor-locale // 各國語言代碼 https://en.wikipedia.org/wiki/Language_localisation // Set the resx file folder path to access services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddSyncfusionBlazor(); // Register the Syncfusion locale service to customize the SyncfusionBlazor component locale culture services.AddSingleton(typeof(ISyncfusionStringLocalizer), typeof(SyncfusionLocalizer)); services.Configure <RequestLocalizationOptions>(options => { // Define the list of cultures your app will support var supportedCultures = new List <CultureInfo>() { new CultureInfo("en-US"), new CultureInfo("zh-TW"), }; // Set the default culture options.DefaultRequestCulture = new RequestCulture("zh-TW"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); #endregion #region EF Core & AutoMapper 使用的宣告 string connectionString = Configuration.GetConnectionString(MagicHelper.DefaultConnectionString); services.AddDbContext <BackendDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString( MagicHelper.DefaultConnectionString))); services.AddCustomServices(); services.AddAutoMapper(c => c.AddProfile <AutoMapping>(), typeof(Startup)); #endregion #region 加入設定強型別注入宣告 services.Configure <TokenConfiguration>(Configuration.GetSection("Tokens")); #endregion #region 加入使用 Cookie & JWT 認證需要的宣告 services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None; }); services.AddAuthentication( MagicHelper.CookieAuthenticationScheme) .AddCookie(MagicHelper.CookieAuthenticationScheme) .AddJwtBearer(MagicHelper.JwtBearerAuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Tokens:ValidIssuer"], ValidAudience = Configuration["Tokens:ValidAudience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])), RequireExpirationTime = true, ClockSkew = TimeSpan.Zero, }; options.Events = new JwtBearerEvents() { OnAuthenticationFailed = context => { context.Response.OnStarting(async() => { context.Response.StatusCode = 401; context.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase = context.Exception.Message; APIResult apiResult = JWTTokenFailHelper.GetFailResult(context.Exception); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(apiResult)); }); return(Task.CompletedTask); }, OnChallenge = context => { ////context.HandleResponse(); return(Task.CompletedTask); }, OnTokenValidated = context => { //Console.WriteLine("OnTokenValidated: " + // context.SecurityToken); return(Task.CompletedTask); } }; }); #endregion #region 新增控制器和 API 相關功能的支援,但不會加入 views 或 pages services.AddControllers(); #endregion #region 修正 Web API 的 JSON 處理 services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; }) .AddJsonOptions(config => { config.JsonSerializerOptions.PropertyNamingPolicy = null; }); #endregion #region 設定 Swagger 中介軟體 services.AddSwaggerGen(); #endregion #region 加入背景服務 var EnableKeepAliveEndpoint = Convert.ToBoolean(Configuration["EnableKeepAliveEndpoint"]); if (EnableKeepAliveEndpoint == true) { services.AddHostedService <KeepAliveHostedService>(); } #endregion #region 使用 HttpContext services.AddHttpContextAccessor(); #endregion #region 相關選項模式 services.Configure <CustomNLog>(Configuration .GetSection(nameof(CustomNLog))); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton <WeatherForecastService>(); #region Syncfusion 元件使用的宣告 services.AddSyncfusionBlazor(); #endregion #region EF Core & AutoMapper 使用的宣告 string foo = Configuration.GetConnectionString(MagicHelper.DefaultConnectionString); services.AddDbContext <SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString( MagicHelper.DefaultConnectionString)), ServiceLifetime.Transient); AddOtherServices(services); services.AddAutoMapper(c => c.AddProfile <AutoMapping>(), typeof(Startup)); #endregion #region 加入使用 Cookie & JWT 認證需要的宣告 services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None; }); services.AddAuthentication( CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Tokens:ValidIssuer"], ValidAudience = Configuration["Tokens:ValidAudience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])), RequireExpirationTime = true, ClockSkew = TimeSpan.Zero, }; options.Events = new JwtBearerEvents() { OnAuthenticationFailed = async context => { context.Response.StatusCode = 401; context.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase = context.Exception.Message; APIResult apiResult = JWTTokenFailHelper.GetFailResult(context.Exception); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(apiResult)); return; }, OnChallenge = context => { //context.HandleResponse(); return(Task.CompletedTask); }, OnTokenValidated = context => { Console.WriteLine("OnTokenValidated: " + context.SecurityToken); return(Task.CompletedTask); } }; }); #endregion #region 新增控制器和 API 相關功能的支援,但不會加入 views 或 pages services.AddControllers(); #endregion #region 修正 Web API 的 JSON 處理 services.AddControllers().AddJsonOptions(config => { config.JsonSerializerOptions.PropertyNamingPolicy = null; }); #endregion #region Localization https://github.com/syncfusion/blazor-locale // 各國語言代碼 https://en.wikipedia.org/wiki/Language_localisation // Set the resx file folder path to access services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddSyncfusionBlazor(); // Register the Syncfusion locale service to customize the SyncfusionBlazor component locale culture services.AddSingleton(typeof(ISyncfusionStringLocalizer), typeof(SyncfusionLocalizer)); services.Configure <RequestLocalizationOptions>(options => { // Define the list of cultures your app will support var supportedCultures = new List <CultureInfo>() { new CultureInfo("en-US"), new CultureInfo("zh-TW"), }; // Set the default culture options.DefaultRequestCulture = new RequestCulture("zh-TW"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); #endregion }