📄 Documentation for Startup.cs
Assembly: IrbyImaging.UI
Author: kvamshi
Created: 01-11-2022
Last Modified: 06-08-2022
📑 Table of Contents
- Overview & Purpose
- Key Functional Areas
- Dependencies & Technologies
- ConfigureServices Method
- Configure Method (HTTP Pipeline)
- Middleware:
NoCacheMiddleware - Usage Examples
- Conclusion
1. Overview & Purpose
The Startup class is the entry point for configuring the ASP.NET Core application. It wires up:
- Dependency Injection (services & options)
- Authentication/Authorization via Azure AD (OpenID Connect)
- Entity Framework Core for data access
- Azure Blob Storage and Key Vault integrations
- Quartz.NET hosted jobs
- Middleware pipeline for security, CORS, sessions & routing
2. Key Functional Areas
- Service Registration (
ConfigureServices) - App Configuration (
Configure) - Security: CSP, cookie policies, OpenID Connect
- Persistence: EF Core, Azure Blob
- Background Jobs: Quartz + hosted services
- Session Management & Caching controls
3. Dependencies & Technologies
| Category | NuGet / Namespace |
|---|---|
| Authentication / Identity | Microsoft.Identity.Web, OpenIdConnect, Identity |
| Web Framework | Microsoft.AspNetCore.* (MVC, Razor Pages, Middleware) |
| Data Access | Microsoft.EntityFrameworkCore |
| Azure Services | Azure.Storage.Blobs, Azure.Security.KeyVault.Secrets |
| Scheduling | Quartz, Quartz.Spi, Quartz.Impl |
| OCR / PDF / Spreadsheet | IronOcr, IronPdf, IronXL, Syncfusion, Bold |
| JSON Serialization | Newtonsoft.Json |
4. ConfigureServices Method
public void ConfigureServices(IServiceCollection services)
{
// 1️⃣ Azure Key Vault
services.AddAzureClients(builder =>
builder.AddSecretClient(Configuration.GetSection("KeyVault")));
services.AddSingleton<IKeyVaultManager, KeyVaultManager>();
// 2️⃣ Authentication
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options => { … });
// 3️⃣ Database & Storage
services.AddDbContext<IrbyContext>();
services.AddScoped(_ => new BlobServiceClient(Configuration["IrbySystemsStorageConnections"]));
// 4️⃣ Application Services (Business + Presentation)
services.AddTransient<IActiveDirectoryService, ActiveDirectoryService>();
services.AddScoped<IAssetManager, AssetManager>();
// … many mappers & services
// 5️⃣ MVC, Razor & JSON options
services.AddControllersWithViews()
.AddNewtonsoftJson(opts => {
opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
.AddRazorRuntimeCompilation();
services.AddRazorPages().AddMicrosoftIdentityUI();
// 6️⃣ CORS
services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins,
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
// 7️⃣ Request Size Limits (900 MB)
services.Configure<IISServerOptions>(opts => opts.MaxRequestBodySize = maxRequestLimit);
services.Configure<KestrelServerOptions>(opts => opts.Limits.MaxRequestBodySize = maxRequestLimit);
services.Configure<FormOptions>(opts => {
opts.MultipartBodyLengthLimit = maxRequestLimit;
});
// 8️⃣ Sessions & Cookies
services.AddSession(opts => {
opts.Cookie.Name = ".Audit.Session";
opts.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opts.Cookie.IsEssential = true;
});
services.ConfigureApplicationCookie(opts => {
opts.ExpireTimeSpan = TimeSpan.FromMinutes(30);
opts.LoginPath = "/MicrosoftIdentity/Account/SignIn";
opts.LogoutPath = "/MicrosoftIdentity/Account/SignOut";
opts.AccessDeniedPath = "/UnAuthorized/Index";
opts.SlidingExpiration = true;
});
services.Configure<CookiePolicyOptions>(opts => {
opts.CheckConsentNeeded = _ => true;
opts.ConsentCookie.SecurePolicy = CookieSecurePolicy.Always;
opts.ConsentCookie.HttpOnly = true;
});
// 9️⃣ Quartz.NET Hosted Jobs
services.AddHostedService<QuartzHostedService>();
services.AddSingleton<IJobFactory, SingletonJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
// Register jobs + schedules
services.AddSingleton<ODSUpdate>();
services.AddSingleton(new JobSchedule(
jobType: typeof(ODSUpdate),
cronExpression: "0 0/45 * 1/1 * ? *"));
// … LegalDashboardUpdate, UAREmail, etc.
}
🔑 Azure Key Vault & Secrets
AddAzureClientsreadsKeyVaultsection fromappsettings.json.IKeyVaultManagerwraps secret retrieval.
🔒 Authentication & Authorization
- OpenID Connect via Azure AD:
"AzureAdLoginInstance": "https://login.microsoftonline.com/", "AzureAdDomain": "contoso.com", "IrbySystemsAppId": "xxxxx-xxxx-xxxx-xxxx", "Tenant": "your-tenant-id", "AzureAdCallbackPath": "/signin-oidc" - All MVC controllers require authenticated users by default.
🗄️ Database & Blob Storage
- Entity Framework:
IrbyContext - Azure Blob:
BlobServiceClientinjected as scoped
🛠️ Application & Presentation Services
- Business logic:
IJobManager,IEmployeeAndFieldOfficeManager, etc. - Presentation mapping:
IComputerMapper,ISafetyEquipmentMapper, …
⚙️ Session, Cookies & CORS
- Global CORS policy: Allow any origin/method/header
- Session cookie named
.Audit.Session - Strict Content-Security-Policy, CookiePolicyOptions
⏰ Quartz Scheduler Jobs
| Job Class | Cron Expression | Schedule Description |
|---|---|---|
ODSUpdate |
0 0/45 * * * ? |
Every 45 minutes |
LegalDashboardUpdate |
0 0 0 * * ? |
Daily at midnight |
UAREmail |
0 0/2 * * * ? |
Every 2 minutes |
ReviewAfterService |
HostedService | Runs as IHostedService |
5. Configure Method (HTTP Pipeline)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// License registrations
IronOcr.License.LicenseKey = "...";
IronPdf.License.LicenseKey = "...";
IronXL.License.LicenseKey = "...";
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("...");
Bold.Licensing.BoldLicenseProvider.RegisterLicense("...");
// Security headers: upgrade-insecure-requests, HSTS
app.Use((ctx, next) => {
ctx.Response.Headers.Append("Content-Security-Policy",
"upgrade-insecure-requests; block-all-mixed-content;");
return next();
});
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseSession();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
// Additional security headers
app.UseMiddleware<NoCacheMiddleware>();
// MVC endpoints
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
🖇️ Request Pipeline Diagram (ASCII)
[ Incoming Request ]
|
Security Headers
|
DeveloperException / HSTS
|
HTTPS Redirection
|
Static Files
|
Cookie Policy
|
Routing
|
Authentication
|
Session
|
Authorization
|
CORS
|
NoCache Middleware
|
MVC / Razor
6. Middleware: NoCacheMiddleware
Prevents any caching across all browsers:
public class NoCacheMiddleware
{
private readonly RequestDelegate _next;
public NoCacheMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext ctx)
{
ctx.Response.OnStarting(state => {
ctx.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
ctx.Response.Headers.Append("Pragma", "no-cache");
ctx.Response.Headers.Append("Expires", "0");
return Task.CompletedTask;
}, null);
await _next(ctx);
}
}
7. Usage Examples
Injecting Blob Storage
public class ReportService
{
private readonly BlobServiceClient _blobClient;
public ReportService(BlobServiceClient blobClient) => _blobClient = blobClient;
public async Task UploadPdfAsync(Stream pdfStream, string container, string blobName)
{
var containerClient = _blobClient.GetBlobContainerClient(container);
await containerClient.UploadBlobAsync(blobName, pdfStream);
}
}
Accessing Key Vault Secrets
public class SecretsDemo
{
private readonly IKeyVaultManager _vault;
public SecretsDemo(IKeyVaultManager vault) => _vault = vault;
public async Task<string> GetDatabasePasswordAsync()
=> await _vault.GetSecretAsync("DbPassword");
}
Scheduling a New Quartz Job
// 1. Create your job
public class CleanupJob : IJob { /* ... */ }
// 2. Register in ConfigureServices
services.AddSingleton<CleanupJob>();
services.AddSingleton(new JobSchedule(
jobType: typeof(CleanupJob),
cronExpression: "0 0 3 * * ?")); // daily at 3 AM
8. Conclusion
🎯 Startup.cs centralizes all critical configuration for:
- Security (Azure AD, CSP, cookies)
- Persistence (EF Core, Blob Storage, Key Vault)
- Background Processing (Quartz jobs, hosted services)
- Web Pipeline (MVC, static files, sessions, CORS)
By following this structure, the application ensures maintainability, testability, and robust security defaults.
Feel free to extend the ConfigureServices or Configure methods to introduce new services, middleware, or routes as your project evolves! 🚀