MVC in C# End to End Glance
1. First: memorize the complete MVC request flow
Be able to draw and explain this without hesitation:
Browser / Client ↓ DNS / Load Balancer / Reverse Proxy ↓ Kestrel ↓ ASP.NET Core Middleware Pipeline ↓ Exception Handling ↓ HTTPS / Static Files ↓ Routing ↓ CORS ↓ Authentication ↓ Authorization ↓ Endpoint Selection ↓ MVC Filter Pipeline ↓ Authorization Filter ↓ Resource Filter ↓ Model Binding ↓ Model Validation ↓ Action Filter ↓ Controller ↓ Action Method ↓ Service / Business Layer ↓ Repository / EF Core ↓ Database / External Services ↓ ActionResult ↓ Result Filter ↓ Razor View Engine / JSON / File / Redirect ↓ Response Middleware ↓ Client
Middleware ordering matters for security and functionality. Microsoft specifically documents typical ordering such as routing before authentication/authorization and notes that middleware runs in registration order for the request and reverse order for the response.
A strong interview answer to “Explain MVC request lifecycle” would be:
The request first reaches Kestrel and moves through the ASP.NET Core middleware pipeline. Routing identifies the endpoint. Authentication establishes user identity and authorization checks access. MVC then executes its filter pipeline, performs model binding and validation, creates the controller through dependency injection, invokes the action, and produces an action result. For a UI application, the Razor view engine renders HTML; for an API it may serialize an object to JSON. The response then travels back through the middleware pipeline.
2. MVC Fundamentals
Q1. What is MVC?
MVC stands for:
Model View Controller
Model
- application/domain data
- validation
- business state
View
- presentation/UI
-
usually
.cshtml - Razor syntax
Controller
- accepts HTTP request
- validates request
- delegates business work
- determines result
Senior answer:
Controllers should remain thin. They shouldn't contain significant business logic or direct infrastructure concerns.
Microsoft similarly recommends delegating business/data logic to services rather than putting it directly inside controllers.
Q2. Why use MVC?
Discuss:
- Separation of concerns
- Maintainability
- Testability
- Parallel development
- Routing
- Dependency injection
- Model binding
- Validation
- Filters
- Razor engine
- Extensibility
Q3. MVC vs Razor Pages?
MVC:
Controller ↓ View
Razor Pages:
Page.cshtml Page.cshtml.cs
Use MVC when:
- application has complex workflows
- many controllers/actions
- clear domain/service architecture
- large enterprise application
Razor Pages can work well for page-oriented applications.
Q4. MVC vs Web API?
In modern ASP.NET Core they share much infrastructure.
MVC commonly:
return View(model);
API:
return Ok(dto);
Both can use:
- Controllers
- Routing
- Model binding
- DI
- Filters
- Authentication
- Authorization
Q5. Controller vs ControllerBase?
ControllerBase
- API functionality
- no View support
Controller
inherits from ControllerBase and adds:
- View()
- ViewData
- ViewBag
- TempData
Typical API:
public class ProductsController : ControllerBase
MVC UI:
public class ProductsController : Controller
3. Controllers and Actions
Know these questions.
Q6. What is a controller?
A class responsible for handling related HTTP requests.
public class ProductController : Controller { public IActionResult Index() { return View(); } }
Q7. What makes a method an MVC action?
Typically a public method on a controller unless marked:
[NonAction]
Q8. What should not exist inside a controller?
Avoid:
complex business rules SQL large EF queries file processing logic email implementation external API implementation complex calculations large mapping code
Prefer:
Controller ↓ Application Service ↓ Domain ↓ Infrastructure
Q9. IActionResult vs ActionResult<T>?
IActionResult:
public IActionResult Get()
Useful when returning different HTTP results.
ActionResult<T>:
public ActionResult<ProductDto> Get(int id)
Better API typing and API documentation.
Q10. Common ActionResults?
Know:
ViewResult PartialViewResult JsonResult ContentResult FileResult RedirectResult RedirectToActionResult ObjectResult OkResult NotFoundResult BadRequestResult UnauthorizedResult ForbidResult StatusCodeResult NoContentResult
4. Routing
Q11. What is routing?
Maps URL → endpoint/controller/action.
Conventional:
app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
Q12. Conventional vs Attribute Routing?
Conventional:
{controller}/{action}/{id?}
Attribute:
[Route("products")] public class ProductController : Controller { [HttpGet("{id:int}")] public IActionResult Get(int id)
Q13. What are route constraints?
Example:
[HttpGet("{id:int}")]
Others:
int long guid bool datetime min max length regex
Q14. What happens when two routes match?
You can get an ambiguous endpoint/action match.
Tech Lead answer should include:
- improve route design
- constraints
- clear HTTP methods
- avoid overlapping patterns
Q15. What are Areas?
Used for logically dividing a large MVC system.
Example:
Areas/ Admin/ Customer/ Support/
5. Model Binding
This is a very common senior interview subject.
Model binding converts incoming request values into C# parameters/objects. Microsoft documents binding from sources such as routes, forms and query strings.
Q16. What is model binding?
Example:
GET /products?id=10
public IActionResult Get(int id)
MVC automatically converts:
"10"
to:
int 10
Q17. Binding sources?
Know:
[FromRoute] [FromQuery] [FromBody] [FromForm] [FromHeader] [FromServices]
Q18. Can multiple parameters use [FromBody]?
Normally no, because request body is read as a single body payload.
Prefer:
public IActionResult Save([FromBody] OrderRequest request)
Q19. What is overposting / mass assignment?
Dangerous:
public IActionResult Update(User user)
Client could potentially submit properties you did not intend to update.
Instead:
public sealed class UpdateUserRequest { public string Name { get; set; } }
Map allowed fields explicitly.
This is an excellent code-review finding.
6. Model Validation
Q20. How does MVC validation work?
Example:
public class CustomerRequest { [Required] public string Name { get; set; } [EmailAddress] public string Email { get; set; } [Range(18, 100)] public int Age { get; set; } }
Controller:
if (!ModelState.IsValid) return View(model);
Q21. DataAnnotations vs FluentValidation/custom validators?
Discuss trade-offs.
DataAnnotations:
- simple
- built in
- close to DTO
External validation approach:
- complex validation
- reusable rule sets
- separation
Q22. Business validation vs request validation?
Very important.
Request validation:
Email required Age must be positive Name max 100 chars
Business rule:
Customer cannot cancel an already-settled order.
Business rules belong in domain/application logic, not merely UI validation.
7. Dependency Injection
This is mandatory for Senior/Lead.
Current .NET DI supports:
- Transient
- Scoped
- Singleton.
Q23. Explain DI.
Instead of:
var service = new OrderService();
Use:
public OrderController(IOrderService service) { _service = service; }
Registration:
builder.Services.AddScoped<IOrderService, OrderService>();
Q24. Explain Transient.
AddTransient<IService, Service>();
New instance whenever requested.
Use for lightweight/stateless services where appropriate.
Q25. Explain Scoped.
AddScoped<IService, Service>();
In an MVC web application:
One instance per request/scope.
EF Core DbContext is scoped by default when registered with AddDbContext.
Q26. Explain Singleton.
AddSingleton<IService, Service>();
One instance for application lifetime.
Must be thread-safe.
Q27. Can Singleton depend on Scoped?
Usually no through normal constructor injection.
Example problem:
Singleton ↓ DbContext (Scoped)
This can effectively capture request-specific scoped state.
Microsoft specifically warns against directly injecting scoped services into singleton services.
Q28. Can Scoped depend on Singleton?
Yes.
Scoped ↓ Singleton
Normally fine.
Q29. What is a captive dependency?
When a long-lived object captures a shorter-lived dependency.
Classic example:
Singleton → Scoped
Tech Lead/code-review question.
Q30. DI vs Service Locator?
Bad:
var service = serviceProvider.GetService<IOrderService>();
everywhere in business code.
Prefer explicit constructor dependencies.
8. Middleware
Q31. What is middleware?
Component in HTTP request/response pipeline.
app.Use(async (context, next) => { // before await next(); // after });
Q32. Middleware order?
Extremely important.
Typical simplified order:
app.UseExceptionHandler(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute(...);
The exact ordering can vary with requirements, but authentication/authorization order and placement relative to routing is particularly important.
Q33. Use, Run, and Map?
Use
continues pipeline.
Run
terminal middleware.
Map
branches pipeline based on path.
Q34. Write custom middleware.
You should know:
public class RequestLoggingMiddleware { private readonly RequestDelegate _next; public RequestLoggingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // before await _next(context); // after } }
9. Middleware vs Filters
Very common Lead interview question.
Middleware
Applies broadly to HTTP pipeline.
Examples:
exception handling request logging correlation IDs authentication CORS compression
Filters
MVC-specific pipeline.
Microsoft documents authorization, resource, action, exception and result-related filter stages.
Know:
Authorization Filter Resource Filter Action Filter Exception Filter Result Filter
Q35. Action filter use case?
Logging action execution:
Before Action Controller Action After Action
Q36. Resource filter?
Runs around much of MVC processing and can execute before model binding.
Potential uses:
- caching
- short-circuiting expensive MVC work
Q37. Exception filter vs exception middleware?
My preferred Senior/Lead answer:
Use global exception-handling middleware for broad application exception handling. Use exception filters when handling behavior specifically tied to MVC action execution.
10. Razor / Views
Q38. What is Razor?
Server-side view syntax.
<h1>@Model.Name</h1>
Q39. Strongly typed View?
@model CustomerViewModel <h2>@Model.Name</h2>
Prefer over dynamic data for important models.
Q40. ViewData vs ViewBag vs TempData?
ViewData
ViewData["Name"]
dictionary.
ViewBag
ViewBag.Name
dynamic wrapper.
TempData
survives into a subsequent request, commonly useful across redirect.
Q41. Partial View vs View Component?
Partial view:
Mainly reusable markup.
View Component:
UI + its own logic/dependencies
Example:
Shopping Cart Navigation Recent Orders
Q42. What is a Layout?
Common page structure.
_header navigation @RenderBody() _footer
Q43. Tag Helper?
Example:
<a asp-controller="Product" asp-action="Details" asp-route-id="@item.Id">
11. State Management
Know difference between:
Cookies Session TempData Cache Database Hidden Fields Query String Claims
Q44. Why shouldn't application data simply be kept in server memory?
In multi-instance architecture:
Request 1 → Server A Request 2 → Server B
Server B may not have Server A's local state.
This leads into:
- stateless applications
- distributed cache
- Redis
- database persistence
12. Caching
Q45. Types of caching?
Prepare:
IMemoryCache IDistributedCache Redis Output Caching Response Caching CDN Database/query caching
Q46. Memory cache vs Distributed cache?
Memory:
Server A memory
Distributed:
Server A ─┐ Server B ─┼→ Redis Server C ─┘
Microsoft notes that multi-server scenarios can require distributed caching to avoid consistency problems associated with non-sticky in-memory caching.
Q47. What is cache invalidation?
Critical Lead question.
Discuss:
- TTL
- absolute expiration
- sliding expiration
- event-based invalidation
- versioned cache keys
- cache-aside
- stale data
- cache stampede
13. Async/Await and Concurrency
Very important Senior area.
Q48. Why async in MVC?
Database/network/file operations are I/O-bound.
var products = await _repository.GetProductsAsync(cancellationToken);
Async prevents a request thread from blocking while waiting for I/O, allowing better scalability.
Microsoft recommends avoiding blocking calls such as .Wait() on asynchronous operations because excessive blocking can cause thread-pool starvation.
Q49. Why is this bad?
var result = GetDataAsync().Result;
or
GetDataAsync().Wait();
Potential:
- thread blocking
- lower scalability
- thread-pool starvation
- historically deadlock problems depending on synchronization context
Prefer:
await GetDataAsync();
Q50. What is CancellationToken?
Example:
public async Task<IActionResult> Get( CancellationToken cancellationToken) { var result = await _service.GetAsync(cancellationToken); return View(result); }
Propagate through:
Controller → Service → Repository → EF Core/HttpClient
Excellent code-review requirement.
Q51. Task vs Thread?
Task represents asynchronous work.
Thread is an OS execution resource.
One request does not mean permanently dedicated thread ownership.
Q52. Task.Run() around database call?
Usually wrong:
await Task.Run(() => db.Products.ToList());
Use native asynchronous I/O:
await db.Products.ToListAsync();
14. EF Core / Data Access
A Senior MVC interview nearly always moves into EF.
Prepare:
Q53. What is DbContext?
Represents database session/unit of work and tracks entity changes.
Q54. Why scoped?
One context per request is a common web application pattern.
Q55. Tracking vs AsNoTracking()?
For read-only query:
var products = await db.Products .AsNoTracking() .ToListAsync();
Avoids unnecessary change tracking.
Q56. What is N+1 query problem?
Example:
1 query → Orders then 100 separate queries → Customers
Solutions can include:
- projection
- Include when appropriate
- explicit query design
- batching
Q57. Include() vs projection?
Instead of loading full objects:
.Include(x => x.Customer)
sometimes better:
.Select(x => new OrderDto { Id = x.Id, CustomerName = x.Customer.Name })
Projection minimizes unnecessary data.
Q58. IEnumerable vs IQueryable?
IQueryable
query expression can be translated to database operation.
IEnumerable
operations may execute in memory after materialization.
Q59. First() vs FirstOrDefault() vs Single()?
Know semantics.
First
expects at least one.
FirstOrDefault
returns default if none.
Single
expects exactly one.
SingleOrDefault
zero or one.
Q60. Optimistic concurrency?
Use concurrency tokens/version columns.
Handle case where another request modified data between read and update.
Q61. Transactions?
Know:
ACID BeginTransaction Commit Rollback transaction boundary isolation levels
Also know not to create huge transactions around external network calls.
Q62. Repository pattern with EF Core—is it required?
Tech Lead answer:
Not automatically.
DbContextandDbSetalready provide repository/unit-of-work-like abstractions. Add repositories when they create meaningful domain/data-access boundaries, not merely to add another pass-through layer.
This is a good trade-off answer.
15. Authentication and Authorization
Senior level must distinguish:
Authentication
Who are you?
Authorization
What are you allowed to do?
Q63. Cookie authentication vs JWT?
MVC web UI often:
Authentication Cookie
API commonly:
Bearer JWT
But architecture determines choice.
Q64. What is a JWT?
Structure:
Header . Payload . Signature
Know:
- issuer
- audience
- expiration
- claims
- signing key
- validation
JWT is normally signed, not inherently encrypted.
Q65. OAuth 2.0 vs OpenID Connect?
OAuth 2:
Authorization / delegated API access
OpenID Connect:
Authentication layer on top of OAuth 2.0
Q66. Role-based vs Policy-based authorization?
Role:
[Authorize(Roles = "Admin")]
Policy:
[Authorize(Policy = "CanApproveClaim")]
Policy-based authorization is usually more flexible for enterprise systems.
Q67. Claims?
Examples:
UserId Department TenantId Permission Role
16. MVC Security — very important for Tech Lead
You should be able to discuss all of these:
Authentication Authorization CSRF XSS SQL Injection Overposting Open Redirect CORS HTTPS HSTS Secure Cookies SameSite Secrets Management Input Validation Output Encoding Security Headers Rate Limiting File Upload Security Logging sensitive information Dependency vulnerabilities
Q68. CSRF?
Attacker tricks authenticated browser into sending an unwanted state-changing request.
MVC form protection uses antiforgery tokens.
Example:
[HttpPost] [ValidateAntiForgeryToken] public IActionResult Save(...)
Microsoft warns that state-changing MVC actions without appropriate antiforgery validation may be vulnerable to CSRF.
Q69. XSS?
Attacker gets malicious script/content rendered to browser.
Protection:
- output encoding
- validate/sanitize appropriate input
- avoid unnecessary raw HTML
- CSP where appropriate
Razor encodes output by default.
Q70. SQL Injection?
Bad:
$"SELECT * FROM User WHERE Name='{name}'"
Prefer parameterization/EF Core.
Q71. CORS?
Controls browser cross-origin access.
Do not say:
CORS is authentication.
It is not.
Q72. HTTPS vs HSTS?
HTTPS encrypts transport.
HSTS tells supported browsers to use HTTPS for subsequent requests for the configured period.
Q73. Secrets?
Never:
string connectionString = "server=...password=MyPassword";
Prefer appropriate configuration/secrets systems such as:
- environment settings
- development user secrets
- Azure Key Vault / cloud secret stores
- managed identity when possible
17. Rate Limiting
Modern Senior interview topic.
Algorithms to know:
Fixed Window Sliding Window Token Bucket Concurrency
ASP.NET Core provides built-in rate-limiting support for these strategies.
Questions:
Q74. Why rate limit?
- abuse control
- resource protection
- fairness
- availability
- cost protection
Q75. Should every endpoint have same limit?
No.
Example:
GET product 1000/min Generate report 10/min Login attempt 5/min
Cost and security matter.
18. HttpClient
Q76. Why not repeatedly do this?
using var client = new HttpClient();
in every request.
Prefer IHttpClientFactory.
Benefits:
- handler lifetime management
- configuration
- named/typed clients
- resilience integration
- logging
Q77. External API resilience?
Discuss:
Timeout Retry Exponential backoff Jitter Circuit breaker Bulkhead/concurrency controls Cancellation Fallback — where appropriate Idempotency
Important:
Don't blindly retry non-idempotent operations.
19. Error Handling
Q78. Global exception handling?
Prefer central handling rather than:
try { } catch(Exception) { }
inside every controller.
Architecture:
Controller ↓ Service ↓ Exception ↓ Global Exception Handler ↓ ProblemDetails/Error Page
Q79. Should we expose stack traces?
No in production responses.
Log diagnostic details securely.
Return safe response.
Q80. Expected error vs unexpected exception?
Example expected:
Customer not found Validation failed Duplicate request
Unexpected:
NullReferenceException Database unavailable Unhandled system failure
Don't use exceptions as normal control flow unnecessarily.
20. Logging and Observability
Prepare:
ILogger<T> Structured logging Log levels Correlation ID Trace ID Metrics Distributed tracing OpenTelemetry Application Insights Health Checks Dashboards Alerts
Q81. Logging levels?
Trace Debug Information Warning Error Critical
Q82. Structured logging?
Better:
_logger.LogInformation( "Order {OrderId} completed for customer {CustomerId}", orderId, customerId);
Instead of concatenated strings.
Q83. What should not be logged?
Avoid sensitive data such as:
passwords authentication tokens credit-card numbers private secrets connection strings sensitive personal information unless specifically controlled
Q84. Correlation ID?
Tracks a transaction across:
Browser ↓ Web App ↓ Order Service ↓ Payment Service ↓ Database
Essential in distributed architectures.
21. Performance
Prepare these questions:
Q85. MVC application is slow. What do you investigate?
Strong Tech Lead sequence:
1. Establish metrics 2. Identify slow endpoint 3. Inspect distributed trace 4. Check application CPU/memory 5. Check thread pool 6. Check database 7. Check external APIs 8. Check query counts/N+1 9. Check GC/memory allocations 10. Check cache 11. Load test 12. Optimize bottleneck 13. Measure again
Not:
I'll immediately add more servers.
Q86. Major ASP.NET performance practices?
Know:
- async I/O
- avoid blocking
- caching
- pagination
- database indexes
- projections
- avoid N+1
- reduce allocations in hot paths
- compression
- CDN
- connection pooling
- load testing
- horizontal scaling
Q87. Horizontal vs Vertical scaling?
Vertical:
4 CPU → 16 CPU
Horizontal:
1 server → 10 servers
22. Testing
Microsoft distinguishes controller unit testing from integration testing: controller unit tests focus on action behavior in isolation, while framework behavior such as routing/model binding is better covered through integration testing.
Prepare:
Unit Test Integration Test Functional Test API Test UI Test Contract Test Performance Test Load Test Security Test
Q88. What should controller unit test verify?
Example:
service called correct result returned correct model returned NotFound returned when necessary BadRequest behavior
Q89. Should you test MVC routing through controller unit test?
No.
Use integration tests for actual routing/model binding/framework behavior.
Q90. Mock everything?
No.
Tech Lead answer:
Mock boundaries and dependencies when isolation has value. Avoid tests that simply verify implementation details.
23. SOLID in MVC
You need to connect SOLID directly to MVC.
S — Single Responsibility
Bad:
OrderController: save order send email generate PDF process payment write SQL
Better:
OrderController OrderService PaymentService NotificationService InvoiceService
O — Open/Closed
Extend behavior without repeatedly modifying central logic.
Strategy/polymorphism commonly demonstrates this.
L — Liskov Substitution
Derived implementations must respect expected behavior of abstraction.
I — Interface Segregation
Bad:
IOrderService { Create(); Delete(); Email(); GeneratePDF(); ProcessPayment(); UploadDocument(); ... }
Split meaningful responsibilities.
D — Dependency Inversion
Controller ↓ IOrderService ↓ OrderService
Depend on abstractions at appropriate boundaries.
24. Architecture Questions
For Tech Lead, MVC questions quickly become architecture questions.
Prepare:
Q91. Layered Architecture?
Presentation Application Domain Infrastructure
Q92. Clean Architecture?
Typical dependency direction:
Web/UI ↓ Application ↓ Domain Infrastructure implements interfaces required by inner layers.
Core business logic should not become dependent on UI/database framework details.
Q93. MVC vs Clean Architecture?
They solve different problems.
MVC:
presentation/application UI pattern.
Clean Architecture:
system dependency/architecture organization.
They can coexist.
Q94. CQRS?
Separate:
Command → changes state Query → reads state
Don't answer:
Every MVC application should use CQRS.
Use where complexity justifies it.
Q95. Mediator pattern?
Decouples request initiator from request handler.
But Lead answer should mention:
Don't add abstractions only because they are fashionable.
Q96. DDD?
Know:
Entity Value Object Aggregate Aggregate Root Repository Domain Service Domain Event Bounded Context Ubiquitous Language
25. Design Patterns Relevant to MVC
Prepare at least:
Creational
Factory Abstract Factory Builder Singleton Prototype
Structural
Adapter Decorator Facade Proxy Composite
Behavioral
Strategy Observer Command Mediator Chain of Responsibility Template Method State
Connect patterns to real application examples.
Example Strategy:
Payment ├── CreditCardPayment ├── ACHPayment └── PayPalPayment
26. API Concerns in an MVC Application
Tech Lead interviews may mix MVC + API.
Prepare:
REST HTTP verbs HTTP status codes DTO API versioning Pagination Filtering Sorting Idempotency Rate limiting OpenAPI Swagger Authentication Authorization Caching ETag Correlation ID ProblemDetails
Q97. HTTP verbs?
GET Read POST Create/action PUT Full replacement/update semantics PATCH Partial update DELETE Delete
Q98. Important HTTP status codes?
200 OK 201 Created 202 Accepted 204 No Content 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 409 Conflict 422 Unprocessable Content 429 Too Many Requests 500 Internal Server Error 502 Bad Gateway 503 Service Unavailable 504 Gateway Timeout
Important interview point:
401 = authentication missing/invalid 403 = authenticated but not permitted
Q99. Idempotency?
Repeating request does not create additional unintended effects.
Useful for operations such as payment/order creation.
Example:
Idempotency-Key: abc-123
27. Configuration
Know:
appsettings.json appsettings.Development.json Environment variables IConfiguration IOptions<T> IOptionsSnapshot<T> IOptionsMonitor<T> Secret stores
Possible question:
Q100. IOptions, IOptionsSnapshot, IOptionsMonitor?
Senior developers should know the general difference:
IOptions basic options access IOptionsSnapshot scoped/request-oriented refreshed snapshot IOptionsMonitor monitors changes and supports notifications
28. Deployment / Production
For Tech Lead:
IIS Kestrel Reverse Proxy Docker Kubernetes Azure App Service Azure Container Apps AKS Load Balancer Application Gateway APIM CDN WAF
Q101. What is Kestrel?
ASP.NET Core's cross-platform web server.
Common production architecture:
Internet ↓ WAF / Load Balancer / Reverse Proxy ↓ Kestrel ↓ ASP.NET Core MVC
Q102. Why reverse proxy?
Potential responsibilities:
TLS termination routing load balancing WAF host management central policies
29. CI/CD Questions
A Tech Lead should understand:
Developer ↓ Git ↓ Pull Request ↓ Build ↓ Static Analysis ↓ Unit Tests ↓ Security Scan ↓ Package ↓ Deploy Dev ↓ Integration Tests ↓ Deploy QA ↓ Approval ↓ Production
Prepare:
Q103. What should CI pipeline validate?
- compile
- warnings
- unit tests
- integration tests where appropriate
- lint/style
- static analysis
- dependency vulnerability checks
- secret detection
- artifact creation
- code coverage
- quality gate
Q104. Deployment strategies?
Know:
Rolling Blue/Green Canary Feature Flags Rollback
30. CODE REVIEW — Senior / Tech Lead Standard
This is one of the most important parts of your request.
When interviewer asks:
“How do you review a pull request?”
Do not answer only:
I check naming standards and bugs.
Give this framework.
1. Correctness
Check:
Does requirement actually work? Happy path? Failure path? Boundary conditions? Null handling? Duplicate requests? Race conditions?
2. Architecture
Check:
Correct layer? Controller thin? Business logic in service/domain? Proper abstraction? Unnecessary coupling? Circular dependency? SOLID? Over-engineering?
3. C# Quality
Check:
Naming Readability Small focused methods Nullability Exception handling using/disposal LINQ misuse Collections Generics Pattern matching Immutability where useful Dead code Duplicate code Magic numbers
4. Async
Check:
async all the way? .Result? .Wait()? Task.Run around I/O? CancellationToken propagated? Fire-and-forget work? Parallel operations safe?
5. Dependency Injection
Check:
Correct lifetime? Singleton thread safety? Scoped dependency captured by Singleton? Service locator? Too many constructor dependencies? Disposable lifecycle?
6. MVC
Check:
Controller thin? Correct route? Correct HTTP verb? ModelState/validation? DTO/ViewModel used? Overposting? Correct ActionResult? PRG pattern for forms?
7. Security
Check:
Authentication? Authorization? Policy/permission? CSRF? XSS? SQL injection? Overposting? Input validation? Secrets? Sensitive logging? CORS? File upload validation? Open redirect? Rate limiting?
8. Database
Check:
N+1? Missing index implications? Loads unnecessary columns? Tracking required? AsNoTracking appropriate? Pagination? Transaction boundary? Concurrency? Long-running query? SaveChanges called repeatedly?
9. Performance
Check:
Blocking I/O? Repeated network requests? Excessive allocations? Huge response? Caching opportunity? Infinite/unbounded query? Multiple DB round trips?
10. Reliability
Check:
Timeout? Retry? Circuit breaker? Cancellation? Idempotency? Partial failure? External dependency failure?
11. Logging
Check:
Useful structured logs? Correct log level? Correlation? PII/secrets? Excessive logging? Exceptions logged centrally?
12. Tests
Check:
Unit tests? Edge cases? Negative tests? Integration tests? Tests meaningful? Tests brittle?
13. Maintainability
Ask:
Can another developer understand and safely change this six months later?
Check:
clarity cohesion coupling comments where necessary documentation naming complexity
31. How I would classify PR comments as Tech Lead
Useful interview answer:
BLOCKER
Must fix before merge.
Examples:
Security vulnerability Data loss Incorrect transaction Authentication bypass Breaking production behavior Serious race condition Secret committed
MAJOR
Should fix.
Incorrect architecture Performance problem Missing error handling Bad DI lifetime Important missing test N+1 query
MINOR
Improvement.
Naming small refactoring readability duplication
NIT
Preference.
formatting minor style
This prevents a Tech Lead from treating:
"rename this local variable"
the same as:
"this endpoint allows unauthorized data modification."
32. Code Review Interview Exercise
Interviewer may give you this:
public class UserController : Controller { private readonly AppDbContext _db; public UserController(AppDbContext db) { _db = db; } [HttpPost] public IActionResult Save(User user) { _db.Users.Add(user); _db.SaveChanges(); return View(user); } }
Ask:
What problems do you see?
A strong Senior/Lead review should mention possibilities such as:
- Entity directly exposed to model binding → overposting risk.
- No explicit antiforgery protection shown for cookie-authenticated MVC form.
- No validation handling shown.
- Synchronous database I/O.
- No cancellation support.
- Authorization requirement isn't visible.
- Controller owns persistence behavior directly; depending on architecture, application/service abstraction may be more appropriate.
- No duplicate/business-rule handling.
- Returning the same view after successful POST can cause form resubmission.
- Consider Post/Redirect/Get.
- No domain/business validation.
- Logging/observability may be needed.
- Error/conflict handling needs design.
- Persisting an incoming entity directly may let users control fields that shouldn't be client-controlled.
A better shape could be:
[Authorize] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Save( CreateUserRequest request, CancellationToken cancellationToken) { if (!ModelState.IsValid) return View(request); var result = await _userService.CreateAsync( request, cancellationToken); return RedirectToAction( nameof(Details), new { id = result.Id }); }
Notice the controller does:
Validate Delegate Return
not:
SQL Business Rules Email Transactions PDF Everything
33. Another Tech Lead Code Review Question
What's wrong?
builder.Services.AddSingleton<OrderService>(); public class OrderService { private readonly AppDbContext _db; public OrderService(AppDbContext db) { _db = db; } }
Answer:
OrderService = Singleton AppDbContext = Scoped
This is a lifetime mismatch/captive dependency.
Better typically:
builder.Services.AddScoped<IOrderService, OrderService>();
34. Another Code Review Question
What's wrong?
public async Task<List<Product>> GetProducts() { return _db.Products .ToList(); }
Method is marked async but performs synchronous DB call and contains no await.
Better:
public async Task<List<Product>> GetProductsAsync( CancellationToken cancellationToken) { return await _db.Products .AsNoTracking() .ToListAsync(cancellationToken); }
35. Senior Scenario Questions
Prepare answers for these.
Scenario 1
Production MVC endpoint suddenly takes 15 seconds. What do you do?
Discuss diagnosis before changing code.
Scenario 2
Application works with one instance but fails when scaled to five servers.
Investigate:
local session memory cache local files static state sticky sessions distributed locking/state
Scenario 3
Two users update the same order simultaneously.
Discuss:
optimistic concurrency row version conflict handling transaction boundaries
Scenario 4
Users occasionally create duplicate orders.
Discuss:
idempotency unique constraints transaction retries duplicate-click prevention
Scenario 5
External payment API is unavailable.
Discuss:
timeout circuit breaker bounded retry idempotency queue/event status model observability
Scenario 6
Memory increases continuously.
Investigate:
static collections singleton state event subscriptions undisposed objects large caches large object allocations DbContext lifetime HttpResponse/request retention memory profiling GC metrics
Scenario 7
API gets 100,000 requests/minute.
Discuss:
horizontal scaling load balancing caching rate limiting async I/O database scalability connection pooling CDN queueing partitioning observability
36. Tech Lead Leadership Questions
Don't prepare only technical questions.
Expect:
Q105. Developer submits poor-quality code. What do you do?
Good answer:
Explain the problem and reasoning, categorize critical vs optional review comments, give examples or standards, help the developer understand the design rather than simply rewriting their code.
Q106. Two senior developers disagree on architecture.
Discuss:
requirements constraints alternatives trade-offs POC if necessary performance security maintainability cost team skills decision record
Not:
I'm the lead, so my decision wins.
Q107. How do you enforce coding standards?
Strong answer:
.editorconfig Roslyn analyzers Sonar/static analysis PR templates automated CI checks unit tests architecture rules security scanning code-review guidelines team agreement
Automate what machines can verify.
Q108. How large should PR be?
Prefer small, focused, reviewable PRs.
Huge PR:
4,000 lines 20 concerns
is much harder to review accurately.
Q109. What do you check before approving PR?
A very strong one-line answer:
Correctness, architecture, security, async/concurrency, data access, performance, reliability, observability, tests and maintainability—not merely formatting.
37. Legacy ASP.NET MVC 5 Questions
If the company has older .NET Framework applications, know:
Global.asax App_Start RouteConfig FilterConfig BundleConfig Web.config System.Web HttpApplication OWIN Forms Authentication ASP.NET Identity HttpContext.Current IIS ActionFilterAttribute AuthorizeAttribute Html Helpers ChildAction ViewEngine
And the migration differences from ASP.NET Core.
Important comparison:
ASP.NET MVC 5 ↓ .NET Framework System.Web IIS-heavy architecture Global.asax / Web.config ASP.NET Core MVC ↓ Modern .NET Cross-platform Kestrel Built-in DI Middleware Program.cs Cloud/container friendly
38. Rapid-Fire Questions You Should Answer in 10–20 Seconds
Practice these without thinking:
- MVC?
- Controller vs ControllerBase?
- ViewModel vs Entity?
- IActionResult?
- ActionResult<T>?
- Routing?
- Attribute routing?
- Model binding?
- Model validation?
- ModelState?
- Middleware?
- Filter?
- Middleware vs filter?
- DI?
- Transient?
- Scoped?
- Singleton?
- Can Singleton inject DbContext?
- Async/await?
- Task vs Thread?
- CancellationToken?
-
Task.Run()for DB call? - EF tracking?
- AsNoTracking?
- IQueryable?
- IEnumerable?
- N+1?
- Include vs Select?
- Transaction?
- Optimistic concurrency?
- Authentication?
- Authorization?
- JWT?
- OAuth?
- OpenID Connect?
- Claims?
- Roles?
- Policies?
- CSRF?
- XSS?
- SQL injection?
- CORS?
- HTTPS?
- HSTS?
- Cookie security?
- Rate limiting?
- Caching?
- Redis?
- Memory cache?
- Session?
- TempData?
- ViewData?
- ViewBag?
- Partial View?
- View Component?
- Razor?
- Tag Helper?
- ILogger?
- Correlation ID?
- Structured logging?
- Health checks?
- Unit test?
- Integration test?
- SOLID?
- Clean Architecture?
- CQRS?
- Repository?
- Unit of Work?
- Factory?
- Strategy?
- Decorator?
- Circuit breaker?
- Retry?
- Timeout?
- Idempotency?
- API versioning?
- Pagination?
- REST?
- 401 vs 403?
- 409?
- 429?
- Kestrel?
- Reverse proxy?
- Docker?
- Horizontal scaling?
- CI/CD?
- Blue/Green?
- Canary?
- Feature flag?
- Code coverage?
- Static analysis?
- Sonar?
- PR quality gate?
- Secret scanning?
- Thread safety?
- Race condition?
- Deadlock?
- Memory leak?
- GC?
- Performance troubleshooting?
If you can answer these 100 rapidly and then go deep when the interviewer asks follow-ups, your MVC preparation is at Senior/Lead level.
39. The Tech Lead mental model I want you to remember
For almost every interview scenario, think in this order:
REQUIREMENT ↓ CORRECTNESS ↓ ARCHITECTURE ↓ ┌──────────────┼──────────────┐ ↓ ↓ ↓ SECURITY RELIABILITY PERFORMANCE ↓ ↓ ↓ AUTH / DATA RETRY / ASYNC / CACHE VALIDATION TIMEOUT DB / SCALE └──────────────┼──────────────┘ ↓ OBSERVABILITY ↓ TESTING ↓ CI/CD ↓ PRODUCTION ↓ MAINTAINABILITY
That is the major difference between a Senior Developer and a Tech Lead.
A Senior Developer may answer:
“I can write this controller correctly.”
A Tech Lead should additionally think:
“Is this the right design? Is it secure? Is it testable? What happens under load? What happens when the database or downstream API fails? Can we monitor it? Can another developer maintain it? Can we deploy and roll it back safely?”
That mindset is what you want to demonstrate in an interview.
If you want, I can turn this next into a real 100-question Senior C# MVC mock interview, where I ask you one question at a time, you answer verbally, and I correct your answer exactly like a Tech Lead interviewer.
I can also turn it into a recurring interview drill so you keep practicing these areas.
Comments
Post a Comment