Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: pp.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = &…
Short answer: builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); builder.Services.AddHealthChecks(); app.MapHealthC…
Short answer: Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS_INSTRUMENTATIONKEY"]); Features: Track…
Short answer: TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production. Explain a bit more using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithP…
Short answer: Claims-based authentication is based on claims — pieces of information about the user (like email, role, or permissions). Explain a bit more Each user has a collection of claims represented as key-value pai…
Short answer: Partial views are used to render reusable page sections (like headers, sidebars). public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", pro…
Short answer: Using SignalR for Real-Time Communication // Hub public class ChatHub : Hub { public async Task SendMessage(string user, string message) => await Clients.All.SendAsync("ReceiveMessage", user, m…
Short answer: Response caching caches the entire HTTP response at the server level — useful for static or rarely changing API responses. Explain a bit more Setup: builder.Services.AddResponseCaching(); var app = builder.…
Short answer: zure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Tr…
Short answer: Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet…
Short answer: public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}")…
Short answer: Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet…
Short answer: Configuration providers are components that load configuration data from various sources. Explain a bit more Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In…
Short answer: public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Us…
Short answer: Hangfire or Quartz.NET for Background Jobs Hangfire Example code app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports…
Short answer: How to Test Minimal APIs? Answer: Minimal APIs are tested using WebApplicationFactory or TestServer. Example: var factory = new WebApplicationFactory<Program>(); Example code var client = factory.Crea…
Short answer: Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck<CustomHealthCheck>("CustomCheck"); app.MapHealthChecks("/health"); Cust…
Short answer: How to Use Serilog or NLog? Serilog Example (Program.cs): builder.Host.UseSerilog((ctx, lc) => lc .WriteTo.Console() .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) ); NLog…
Short answer: What Frameworks Are Commonly Used? Answer: xUnit – Popular, lightweight, supports parallel testing. NUnit – Rich assertion library. MSTest – Microsoft-supported, integrated in Visual Studio. Most modern ASP…
Short answer: ASP.NET Core Data Protection API provides secure cryptographic APIs for: Encrypting cookies and tokens Protecting form data Persisting secure keys (across app restarts) Setup: builder.Services.AddDataProtec…
Short answer: ASP.NET Core Data Protection API provides secure cryptographic APIs for: Encrypting cookies and tokens Protecting form data Persisting secure keys (across app restarts) Setup: builder.Services.AddDataProtec…
Short answer: Compiled queries improve performance by caching query translation. Example code private static readonly Func<AppDbContext, decimal, IEnumerable<Product>> _getExpensiveProducts = EF.CompileQuery(…
Short answer: Rate Limiting Middleware in .NET 8 builder.Services.AddRateLimiter(options => { options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => RateLimitPartition.GetFi…
Short answer: How to Enable Application Insights? Answer: Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS…
Short answer: How to Use Moq for Mocking Dependencies? Answer: Moq creates fake implementations of interfaces to control behavior during tests. Example: var mockRepo = new Mock<IProductRepository>(); mockRepo.Setup…
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: pp.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = "Error" }; } } 🧩 19.
pp.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = "Error" }; } } 🧩 19. {
public void OnException(ExceptionContext context)
{
context.Result = new ViewResult { ViewName = "Error" };
}
} 🧩 19. How to return partial views? Partial views are used to render reusable page sections (like headers, sidebars). Example: public IActionResult ProductList()
{
var products = _service.GetAll();
return PartialView("_ProductListPartial", products);
} In Razor: @Html.Partial("_ProductListPartial", Model.Products) 🧾 20. Explain Razor Pages vs MVC. Feature Razor Pages MVC Structure Page-based (.cshtml + .cshtml.cs) Controller + View Best For Simple or CRUD pages Complex or large web apps URL /Products/Edit → /Pages/Products/Edit.cshtml /Products/Edit → ProductController.Edit() Code Location In the same file (PageModel) Separate Controller class Example: Razor Pages are like simplified MVC without controllers — great for admin dashboards or forms. Dependency Injection (DI)
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); builder.Services.AddHealthChecks(); app.MapHealthChecks("/health");
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS_INSTRUMENTATIONKEY"]); Features: Track requests, exceptions, and dependencies Live metrics and dashboards Custom events and telemetry 9⃣ How to Monitor Performance and Uptime?
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production.
using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Password") .Build(); wait sqlContainer.StartAsync(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlServer(sqlContainer.GetConnectionString()) .Options; // Use context in tests ✅ Benefits: Real database behavior CI/CD friendly Close to production setup Deployment & Hosting How to Deploy an ASP.NET Core App to IIS? TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production.
using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Password") .Build(); wait sqlContainer.StartAsync(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlServer(sqlContainer.GetConnectionString()) .Options; // Use context in tests ✅ Benefits: Real database behavior CI/CD friendly Close to production setup Deployment & Hosting How to Deploy an ASP.NET Core App to IIS? TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production. Example: using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Password") .Build(); wait sqlContainer.StartAsync(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlServer(sqlContainer.GetConnectionString()) .Options; // Use context in tests ✅ Benefits: Real database behavior CI/CD friendly Close to production setup Deployment & Hosting How to Deploy an ASP.NET Core App to IIS? IIS (Internet Information Services) can host ASP.NET Core apps via the ASP.NET Core Module, which forwards requests to Kestrel. Steps: TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production. Example: using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Password") .Build(); wait sqlContainer.StartAsync(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlServer(sqlContainer.GetConnectionString()) .Options; // Use context in tests ✅ Benefits: Real database behavior CI/CD friendly Close to production setup Deployment & Hosting How to Deploy an ASP.NET Core App to IIS? IIS (Internet Information Services) can host ASP.NET Core apps via the ASP.NET Core Module, which forwards requests to Kestrel. Steps:
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Claims-based authentication is based on claims — pieces of information about the user (like email, role, or permissions).
Each user has a collection of claims represented as key-value pairs.
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Partial views are used to render reusable page sections (like headers, sidebars). public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", products); In Razor: Follow : @Html.Partial("_ProductListPartial", Model.Products) 🧾 20. Partial views are used to render reusable page sections (like headers, sidebars).
public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", products); In Razor: Follow : @Html.Partial("_ProductListPartial", Model.Products) 🧾 20. Partial views are used to render reusable page sections (like headers, sidebars). Example: public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", products); In Razor: Follow : @Html.Partial("_ProductListPartial", Model.Products) 🧾 20. Explain Razor Pages vs MVC. Feature Razor Pages MVC Structure Page-based (.cshtml + .cshtml.cs) Controller + View Best For Simple or CRUD pages Complex or large web apps URL /Products/Edit → /Pages/Products/Edit.cshtml /Products/Edit → ProductController.Edit() Code Location In the same file (PageModel) Separate Controller class Example: Razor Pages are like simplified MVC without controllers — great for admin dashboards or forms. Dependency Injection (DI) Partial views are used to render reusable page sections (like headers, sidebars). Example: public IActionResult ProductList() var products = _service.GetAll(); return PartialView("_ProductListPartial", products); In Razor: Follow : @Html.Partial("_ProductListPartial", Model.Products) 🧾 20. Explain Razor Pages vs MVC. Feature Razor Pages MVC Structure Page-based (.cshtml + .cshtml.cs) Controller + View Best For Simple or CRUD pages Complex or large web apps URL /Products/Edit → /Pages/Products/Edit.cshtml /Products/Edit → ProductController.Edit() Code Location In the same file (PageModel) Separate Controller class Example: Razor Pages are like simplified MVC without controllers — great for admin dashboards or forms. Dependency Injection (DI)
ShopNest’s product edit form posts to an MVC action. Model binding fills a ProductEditVm; the action validates and redisplay the view on errors.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Using SignalR for Real-Time Communication // Hub public class ChatHub : Hub { public async Task SendMessage(string user, string message) => await Clients.All.SendAsync("ReceiveMessage", user, message); } // Client (JavaScript) const connection = new signalR.HubConnectionBuilder() .withUrl("/chathub") .build(); connection.on("ReceiveMessage", (user, message) => { console.log(`${user}: ${message}`); }); await…
connection.start(); await connection.invoke("SendMessage", "Alice", "Hello!");
Using SignalR for Real-Time Communication // Hub public class ChatHub : Hub
{
public async Task SendMessage(string user, string message) =>
await Clients.All.SendAsync("ReceiveMessage", user, message); } // Client (JavaScript) const connection = new signalR.HubConnectionBuilder() .withUrl("/chathub") .build(); connection.on("ReceiveMessage", (user, message) => { console.log(`${user}: ${message}`); }); await connection.start();
await connection.invoke("SendMessage", "Alice", "Hello!");
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Response caching caches the entire HTTP response at the server level — useful for static or rarely changing API responses.
Setup: builder.Services.AddResponseCaching(); var app = builder.Build(); pp.UseResponseCaching(); Controller Example: [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)] [HttpGet] public IActionResult GetTime() => Ok(DateTime.Now); ✅ The response is cached for 60 seconds — subsequent requests are served faster. {
return Ok(new { Category = category, Time = DateTime.Now });
} ✅ Benefits: Works with authenticated users. Supports vary-by parameters, headers, and policies. Integrates well with minimal APIs and Razor pages. 🗜 7. How to compress responses? Use response compression middleware to reduce payload size for clients. Setup: builder.Services.AddResponseCompression(options => {
{
var data = await _service.GetDataAsync(); // Non-blocking call
return Ok(data);
} ✅ Benefits: Frees threads while waiting for I/O (e.g., DB, HTTP calls). Improves scalability and throughput. Essential for high-traffic APIs and cloud-native apps. ❌ Avoid Task.Result or .Wait() — they block threads and reduce performance. ⚡ 9. How to optimize startup performance? To improve startup and cold-boot performance: ✅ Tips:
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: zure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Track metrics, uptime Health Checks ASP.NET Core HealthChecks Expose /health endpoints This gives a complete production-ready workflow from… deployment… to…… monitoring.
zure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Track metrics, uptime Health Checks ASP.NET Core HealthChecks Expose /health endpoints This gives a complete production-ready workflow from deployment to… monitoring. dvanced & Modern Topics Middleware Pipeline in Depth ASP.NET Core handles HTTP requests through a middleware pipeline, which is a sequence of components where each can: Inspect or modify the request Call the next middleware Short-circuit the pipeline Pipeline Flow: Request -> Middleware1 -> Middleware2 ->…… {
public async Task SendMessage(string user, string message) => wait Clients.All.SendAsync("ReceiveMessage", user, message); } // Client (JavaScript) const connection = new signalR.HubConnectionBuilder() .withUrl("/chathub") .build(); connection.on("ReceiveMessage", (user, message) => { console.log(`${user}: ${message}`); }); wait connection.start(); wait connection.invoke("SendMessage", "Alice", "Hello!"); 5⃣ Background Services (IHostedService) For long-running tasks or scheduled jobs Implement IHostedService or extend BackgroundService public class TimedWorker : BackgroundService
{ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("Running background task"); wait Task.Delay(10000, stoppingToken); }
}
} builder.Services.AddHostedService<TimedWorker>(); ✅ Good for periodic jobs, email processing, queue consumers. 6⃣ Hangfire or Quartz.NET for Background Jobs Hangfire Example: pp.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like scheduling and clustered execution. 7⃣ Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck<CustomHealthCheck>("CustomCheck"); pp.MapHealthChecks("/health"); Custom Health Check Example: public class CustomHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken token) => Task.FromResult(HealthCheckResult.Healthy("Everything OK")); } 8⃣ Rate Limiting Middleware in .NET 8 builder.Services.AddRateLimiter(options => { options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.Remo teIpAddress?.ToString()!, _ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 2 })); }); pp.UseRateLimiter(); ✅ Helps protect APIs from abuse or DoS attacks. 9⃣ DataAnnotations for Validation public class Product
{ [Required] public string Name { get; set; } [Range(1, 100)] public decimal Price { get; set; }
} Works with model binding Automatic client & server-side validation with Razor or API endpoints 🔟 Global Exception Logging pp.UseExceptionHandler(errorApp => { errorApp.Run(async context => {
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet restore COPY .
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15.
How do you pass data from controller to view?
public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use: public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); }
} Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use:
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Docker allows running ASP.NET Core apps in containers, portable across environments. Dockerfile Example: # Build stage FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app COPY *.csproj ./ RUN dotnet restore COPY .
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Configuration providers are components that load configuration data from various sources.
Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vault User Secrets (for local dev) Custom providers (you can build your own) builder.Configuration .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args); Each provider plugs into the same configuration system, so you can access everything via IConfiguration. Configuration providers are components that load configuration data from various sources. Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vault User Secrets (for local dev) Custom providers (you can build your own)
builder.Configuration .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args); Each provider plugs into the same configuration system, so you can access everything via IConfiguration. Configuration providers are components that load configuration data from various sources. Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vault User Secrets (for local dev) Custom providers (you can build your own) Example: builder.Configuration .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args); Each provider plugs into the same configuration system, so you can access everything via IConfiguration. Configuration providers are components that load configuration data from various sources. Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vault User Secrets (for local dev) Custom providers (you can build your own) Example: builder.Configuration .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args); Each provider plugs into the same configuration system, so you can access everything via IConfiguration. 🔐 3. How do you manage secrets in development? In development, never store passwords, API keys, or connection strings in code or ppsettings.json. Use User Secrets — a safe way to store secrets outside the project tree. 🧰 4. What is User Secrets in ASP.NET Core? User Secrets are a local, developer-only configuration storage that keeps sensitive data out of source control. Setup: Enable secrets: dotnet user-secrets init
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15.
How do you pass data from controller to view?
public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use: public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use: public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use: public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter] public IActionResult Index() => View(); 📤 15. How do you pass data from controller to view? You can use:
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Hangfire or Quartz.NET for Background Jobs Hangfire
app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like scheduling and clustered execution.
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: How to Test Minimal APIs? Answer: Minimal APIs are tested using WebApplicationFactory or TestServer. Example: var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/products");
var products = await response.Content.ReadFromJsonAsync<List<Product>>(); Assert.NotEmpty(products);
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck<CustomHealthCheck>("CustomCheck"); app.MapHealthChecks("/health"); Custom Health Check Example: public class CustomHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken token) => Task.FromResult(HealthCheckResult.Healthy("Everything OK")); }
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: How to Use Serilog or NLog? Serilog Example (Program.cs): builder.Host.UseSerilog((ctx, lc) => lc .WriteTo.Console() .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) ); NLog
Install NLog.Extensions.Logging package Add NLog.config file Configure in Program.cs: builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(LogLevel.Information); builder.Host.UseNLog(); ✅ Both support structured logging, sinks, filtering, and rolling files.
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: What Frameworks Are Commonly Used? Answer: xUnit – Popular, lightweight, supports parallel testing. NUnit – Rich assertion library. MSTest – Microsoft-supported, integrated in Visual Studio. Most modern ASP.NET Core projects use xUnit + Moq.
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: ASP.NET Core Data Protection API provides secure cryptographic APIs for: Encrypting cookies and tokens Protecting form data Persisting secure keys (across app restarts) Setup: builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys")) .SetApplicationName("MyApp"); You can use it directly: var protector =………… _provider.CreateProtector("MyPurpose"); var encrypted =…
protector.Protect("secret-data"); var decrypted = protector.Unprotect(encrypted); ✅ Data Protection is the backbone for: Cookie Authentication CSRF Tokens TempData encryption 🧠 Summary Concept Description Best For In-memory caching Stores data in server memory Single-server or dev Distributed caching Shared cache (Redis, SQL) Scalable apps Response caching Caches HTTP responses Public/static data Output caching (.NET 8) Advanced, user-aware caching Dynamic APIs Response compression Gzip/Brotli for responses Large payloads sync/await Non-blocking I/O High concurrency Startup optimization Faster app boot Cloud apps… ASP.NET Core Data…… var encrypted = protector.Protect("secret-data");
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: ASP.NET Core Data Protection API provides secure cryptographic APIs for: Encrypting cookies and tokens Protecting form data Persisting secure keys (across app restarts) Setup: builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys")) .SetApplicationName("MyApp"); You can use it directly: var protector =………… _provider.CreateProtector("MyPurpose"); var encrypted =…
protector.Protect("secret-data"); var decrypted = protector.Unprotect(encrypted); ✅ Data Protection is the backbone for: Cookie Authentication CSRF Tokens TempData encryption 🧠 Summary Concept Description Best For In-memory caching Stores data in server memory Single-server or dev Distributed caching Shared cache (Redis, SQL) Scalable apps Response caching Caches HTTP responses Public/static data Follow : Output caching (.NET 8) Advanced, user-aware caching Dynamic APIs Response compression Gzip/Brotli for responses Large payloads Async/await Non-blocking I/O High concurrency Startup optimization Faster app boot… ASP.NET Core Data……
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Compiled queries improve performance by caching query translation.
private static readonly Func<AppDbContext, decimal, IEnumerable<Product>> _getExpensiveProducts = EF.CompileQuery((AppDbContext ctx, decimal price) => ctx.Products.Where(p => p.Price > price)); var result = _getExpensiveProducts(_context, 1000); 🔍 19. Pool Size=5; uthentication & Authorization
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: Rate Limiting Middleware in .NET 8 builder.Services.AddRateLimiter(options => { options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.Remo teIpAddress?.ToString()!, _ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 2 })); }); app.UseRateLimiter(); ✅ Helps protect…
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: How to Enable Application Insights? Answer: Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS_INSTRUMENTATIONKEY"]); Features: Track requests, exceptions, and dependencies Live metrics and dashboards Custom events and telemetry
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Short answer: How to Use Moq for Mocking Dependencies? Answer: Moq creates fake implementations of interfaces to control behavior during tests. Example: var mockRepo = new Mock<IProductRepository>(); mockRepo.Setup(x => x.GetAll()).Returns(new List<Product> { new Product { Id = 1, Name = "Laptop" } });
var service = new ProductService(mockRepo.Object);
var products = service.GetAll(); Assert.Single(products); ✅ Use .Setup(), .Verify(), and .Returns() to simulate behavior.
ShopNest admin screens use MVC: controller loads data, Razor view renders HTML, Tag Helpers build forms safely.