100% found this document useful (1 vote)
83 views64 pages

ASP.NET Core Web API Design Patterns

The document outlines key concepts and best practices for building and managing ASP.NET Core Web APIs, covering topics such as the advantages of ASP.NET Core over older frameworks, RESTful principles, API versioning strategies, and design patterns like CQRS and the Repository pattern. It also discusses middleware, dependency injection, security practices including JWT and OAuth2, data access with Entity Framework Core, and performance optimization techniques like caching and rate limiting. Additionally, it addresses multi-tenancy, backward compatibility, and handling of long-running operations, providing a comprehensive guide for developers working with ASP.NET Core Web APIs.

Uploaded by

vinshet116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
83 views64 pages

ASP.NET Core Web API Design Patterns

The document outlines key concepts and best practices for building and managing ASP.NET Core Web APIs, covering topics such as the advantages of ASP.NET Core over older frameworks, RESTful principles, API versioning strategies, and design patterns like CQRS and the Repository pattern. It also discusses middleware, dependency injection, security practices including JWT and OAuth2, data access with Entity Framework Core, and performance optimization techniques like caching and rate limiting. Additionally, it addresses multi-tenancy, backward compatibility, and handling of long-running operations, providing a comprehensive guide for developers working with ASP.NET Core Web APIs.

Uploaded by

vinshet116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Architecture, Design & Patterns

1. What are the benefits of using [Link] Core Web API vs older [Link] Web
API on .NET Framework?
Answer: [Link] Core is cross-platform, has improved performance (lightweight,
modular, side-by-side versions), built-in dependency injection, unified request
pipeline (middleware), better support for cloud native / containerization, and more
frequent updates.

2. Explain RESTful API principles, and how you would enforce them in a Web API.
Answer: REST principles include statelessness, uniform interface, resource naming
via URI, use of HTTP verbs (GET/POST/PUT/DELETE etc.), content negotiation,
proper HTTP status codes, self-descriptive messages, maybe HATEOAS etc.
Enforce via controllers focused on resources, DTOs, consistent naming, using HTTP
status codes properly, content negotiation, versioning etc.

3. What is API versioning, and what strategies exist for versioning Web APIs in
[Link] Core?
Answer: API versioning allows evolving an API without breaking clients. Strategies:
URL versioning (e.g. /api/v1/), query string versioning (e.g. ?v=1), header
versioning (custom headers or Accept header), media type versioning. In [Link]
Core there is [Link] package to support various
strategies.

4. Explain CQRS (Command Query Responsibility Segregation) and when to use


it in a Web API.
Answer: CQRS separates read operations (queries) from write operations
(commands). This can lead to different models/data stores for read vs write. Useful
for high complexity / scale, when read and write loads differ, or when you want
optimized read paths, maybe event sourcing.

5. What is the Repository & Unit of Work pattern? Explain how you would
implement them with EF Core in an [Link] Core Web API.
Answer: Repository abstracts data access, Unit of Work groups changes so that
multiple operations either all succeed or all fail. With EF Core: repository can wrap
DbSet operations, Unit of Work is the DbContext instance (which tracks changes and
then SaveChanges / SaveChangesAsync). One must also be aware of lifetime of
DbContext (scoped), transactions, concurrency.

6. How would you design for multi-tenancy in a Web API?


Answer: Multi-tenancy can be implemented via database per tenant, schema per
tenant, or shared schema with tenant discriminator column. Also need to consider
authentication/authorization per tenant, isolation, configuration per tenant. Use
middleware to identify tenant (based on domain, header, bearer token claim, etc.),
then switch context (DI, database provider) accordingly.

7. Explain how you would handle backward compatibility when evolving an API.
Answer: Keep old versions running alongside new ones, deprecate but not remove
functionality abruptly, use versioning (URL/header etc.), backward compatible
changes only (non-breaking changes first), communicate to consumers, possibly
provide adapters.
8. What is Event Sourcing, and how might you pair that with Web APIs?
Answer: Event Sourcing is storing state changes as a sequence of events rather
than storing the current state directly. Useful for audit, replayability, reconstructing
state. In a Web API, commands may trigger events that are persisted; reads may
query event projections. Might combine with CQRS for separating writes (events) and
reads (projections).

9. Explain the Saga pattern and how you would implement distributed
transactions using it.
Answer: Saga is a pattern for managing long-running or distributed transactions by
breaking them into a sequence of local transactions, each with a compensating
action. Implementation could use message queues, orchestration or choreography,
ensure eventual consistency. For example, in microservices: service A does action,
publishes event; service B listens and does its part; if something fails, compensating
events reverse earlier steps.

10. How do you decide between synchronous vs asynchronous endpoints in a


Web API?
Answer: Use asynchronous when operations are I/O bound and likely to wait
(database calls, network calls, file I/O) to avoid blocking threads and to handle many
concurrent requests. Synchronous may suffice if operations are compute-bound or
quick, but avoid for blocking I/O. Also consider client needs (timeout etc.).

Middleware, Pipeline, Hosting, Startup & Configuration


11. What is middleware in [Link] Core? How does the request pipeline work?
Answer: Middleware are components in the request/response pipeline; each
receives an HTTP context, does some work, either short-circuits or passes to next
component. Configuration in [Link]/[Link] using
UseMiddleware(...), Use(...), Map(...), UseEndpoints(...) etc. The
order of middleware matters (e.g. error handling, authentication, static files etc.).

12. How do you add global exception handling in [Link] Core Web API?
Answer: Create custom error-handling middleware (or use built-in
UseExceptionHandler), capture unhandled exceptions, log them, return
standardized error responses. Can also use filters (ExceptionFilterAttribute) but
middleware works more globally including in non-MVC parts.

13. Explain how dependency injection works in [Link] Core, and the different
service lifetimes.
Answer: [Link] Core has built-in IoC container; you register services in
ConfigureServices with lifetimes: Singleton (single instance for app), Scoped
(one per request), Transient (new each time). The container resolves
dependencies, typically via constructor injection; also supports IServiceProvider
etc.

14. How do you handle configuration ([Link] / environment variables /


secrets) in a Web API?
Answer: Use IConfiguration injected via DI. Use [Link],
appsettings.{Environment}.json, environment variables, secret stores (e.g.
Azure Key Vault). Use Options pattern (IOptions<T> / IOptionsMonitor<T> /
IOptionsSnapshot<T>) for strongly typed configuration.

15. What is the difference between IOptions, IOptionsMonitor, and


IOptionsSnapshot?
Answer: IOptions<T> gives a singleton snapshot at startup;
IOptionsSnapshot<T> supports scoped services and picks up changes for that
environment (useful in development) per request; IOptionsMonitor<T> allows for
change notifications at runtime, with live changes (if configuration supports reloading,
e.g. file).

16. Explain how to host an [Link] Core Web API in IIS vs Kestrel vs reverse
proxy (NGINX, Apache).
Answer: Kestrel is the cross-platform web server built into [Link] Core; by itself
can serve HTTP requests. In production often use Kestrel behind a reverse proxy
(e.g. IIS on Windows, NGINX on Linux) for features like port binding, SSL
termination, load balancing. For hosting in IIS, use IIS Integration middleware.

17. What is the difference between minimal APIs and traditional controllers in
[Link] Core? When would you use minimal APIs?
Answer: Minimal APIs (introduced in .NET 6+) allow defining HTTP endpoints with
minimal ceremony (no controllers, light setup, using lambdas). More lightweight,
good for microservices or simple endpoints. Controllers give more structure (filters,
attributes etc.), better for larger APIs that need separation, versioning, policies.

18. What is endpoint routing (UseRouting, UseEndpoints, MapControllers)?


Answer: Routing determines how URL paths map to handlers. In [Link] Core,
you use UseRouting() to add the routing middleware, then later
UseEndpoints(...) to map controllers, razor pages, etc. MapControllers()
tells the endpoint routing to use controller action endpoints. The order relative to
middleware like authentication, CORS is important.

19. How do you configure CORS in [Link] Core? What are the security
implications?
Answer: Add the CORS services in ConfigureServices, e.g.
[Link](...), define policies (origins, methods, headers), then in
middleware using [Link](...) or attributes [EnableCors]. Security
implications: overly permissive CORS allows other origins to make requests; must
limit origins, methods, headers; also consider credentials.

20. How are certificates used in [Link] Core for HTTPS, client certificates, and
how to configure them?
Answer: HTTPS via Kestrel or via reverse proxy; in Kestrel configure server
certificate via UseHttps() or ConfigureKestrel() in [Link]/Startup.
Client certificates: configure mutual TLS in Kestrel, validate client certificate in
custom middleware or via options. Managing certificate lifecycle/security is important.
Security
21. Explain how JWT (JSON Web Tokens) are used for authentication/authorization
in Web API.
Answer: JWT is issued by an identity provider (after login), includes claims, signed
(optionally encrypted). Client sends JWT in Authorization: Bearer <token>
header. API middleware validates token signature, checks claims, expiration, etc.
Then authorization (roles, claims) decide what actions are allowed.

22. What is OAuth2 vs OpenID Connect? When to use each?


Answer: OAuth2 is an authorization framework; OpenID Connect is identity layer on
top of OAuth2. Use OAuth2 when granting limited permissions to resources (e.g.
third-party apps). Use OpenID Connect when you need authentication and identity
information (sign in, user profile).

23. Explain role‐based and claim‐based authorization in [Link] Core.


Answer: Role-based: assign roles (strings) to users, check via
[Authorize(Roles="Admin")]. Claim-based: more flexible, use claims
(type/value), maybe custom claims for user properties, policy based authorization
that checks certain claims or combinations thereof.

24. How do you implement refresh tokens securely?


Answer: On login issue an access token (short expiry) plus a refresh token (longer
expiry). Store refresh tokens securely on server side (e.g. in DB). When refresh token
is used, validate, issue new access token + refresh token, invalidate old refresh
token. Protect against refresh token reuse or theft (rotate, blacklisting).

25. What is token revocation / how to revoke JWT tokens?


Answer: Since JWTs are stateless, revocation is more complex. Strategies:
maintain a blacklist of invalidated tokens or use short expiry and rely on refresh token
revocation. Another approach is to include a token version or jti claim, check version
in DB.

26. How do you prevent common web API attacks (e.g. SQL injection, XSS, CSRF)?
Answer: Use parameterized queries / ORMs (EF Core) to avoid SQL injection. For
XSS, ensure any data sent to clients is sanitized / proper encoding. CSRF is less of
an issue for APIs called from client apps (if following CORS and using token auth),
but if cookies used for auth then anti-CSRF tokens are needed. Also input validation,
output encoding.

27. What is HMAC authentication, and how can it be used in Web APIs?
Answer: HMAC (Hash-based Message Authentication Code) is a way to sign
requests (headers + payload) such that server can verify authenticity and integrity.
The client and server share secret key; client computes signature, server recomputes
and compares. Useful for APIs without stateful tokens or in certain security models
(IoT etc.).

28. Explain how to enforce HTTPS and best practices for secrets management.
Answer: Force HTTPS in middleware (UseHttpsRedirection), configure Kestrel
or proxy correctly. Redirect HTTP to HTTPS. Use HSTS. For secrets: do not store in
code or config in source control; use environment variables, secret stores (Azure Key
Vault, AWS Secret Manager), use user secrets in development, limit permissions.
29. What is identity server (e.g. IdentityServer4 / Duende IdentityServer), and how
to integrate with Web API?
Answer: IdentityServer is a framework implementing OAuth2 and OpenID Connect.
Provides token issuance, authentication, authorization, etc. Web API integrates by
protecting endpoints with JWT Bearer middleware, configuring the API as a resource
server in IdentityServer, validating tokens.

30. How would you handle authorization for microservices (distributed system)?
Answer: Use central auth service / identity server; use JWT or similar tokens
passed between services; service‐to‐service authentication (client credentials flow
etc.); include claims/principals indicating permissions; use policy based authorization.
Also consider network security (TLS), API gateways, fine-grained scopes.

Data Access & Persistence


31. How does Entity Framework Core handle migrations? What are constraints or
gotchas?
Answer: EF Core supports code-first or model-first migrations. Add-Migration,
Update-Database etc. Gotchas: avoiding data loss in schema changes, handling
large databases, avoiding expensive operations (e.g. dropping/recreating large
tables), being careful with non-nullable columns, renames vs recreate, multiple
environments, production vs dev migrations.

32. What is lazy loading vs eager loading vs explicit loading in EF Core? When to
use each?
Answer: Eager loading fetches related entities in the same query (Include). Lazy
loading loads related entities when accessed (requires proxy support). Explicit
loading is when you explicitly call .Load() on navigation property. Use eager when
you know the relationship required; lazy when you rarely use and want to defer;
explicit when selective on demand.

33. How to handle concurrency conflicts in EF Core?


Answer: Use concurrency tokens (e.g. [ConcurrencyCheck] or
rowversion/timestamp). When SaveChanges error
(DbUpdateConcurrencyException) occurs, decide merge strategy: client wins, store
wins, manual merge, prompt user etc.

34. What is no-tracking queries, and when should you use them?
Answer: No-tracking queries (via AsNoTracking()) tell EF not to track entities in
the change tracker. Good for read-only operations, better performance, less memory;
bad if you need updates on the entities.

35. How do you optimize database access for high load (caching, batching, bulk
operations)?
Answer: Use caching (in-memory, distributed like Redis), minimize number of
queries (use eager loading, avoid N+1 problem), batch operations (bulk
inserts/updates), use stored procedures if needed, optimize queries (indexes), use
compiled queries, use scaling (read replicas), connection pooling.
36. Explain using Dapper vs EF Core. When would you prefer Dapper?
Answer: Dapper is lightweight micro-ORM, very fast, low overhead, good for simple
queries or where performance is critical. EF Core is full-feature, tracking,
relationships, LINQ etc. Use Dapper when you need raw SQL, speed, control,
simpler mapping.

37. How do you handle long running database operations?


Answer: Use async methods; maybe background processing; might offload heavy
work; avoid blocking HTTP requests for too long; consider job queues; consider
streaming large data; set proper command timeouts; possibly use batching.

38. What is database pooling, and how is it managed in EF Core / SQL Server /
other providers?
Answer: Connection pooling means reusing open database connections to avoid
overhead. Usually handled by [Link] provider automatically. EF Core passes
through to underlying [Link]. You configure connection string and settings (max
pool size etc.).

39. How do you perform database retry logic with transient failures (e.g. network
blips)?
Answer: EF Core supports retry via EnableRetryOnFailure in
DbContextOptions, or custom retry policies. For more advanced control, use Polly
or similar libraries around database calls.

40. How do you map complex types / owned types / value objects in EF Core?
Answer: EF Core supports owned entity types (using Owned attribute or
OwnsOne() / OwnsMany() in fluent API). They map as part of parent entity (same
table or separate depending on configuration). Also value objects can be mapped as
owned types.

Performance, Scalability & Monitoring


41. How do you do caching in Web API? Difference between in-memory and
distributed cache.
Answer: In-memory cache (using IMemoryCache) is local to one instance; fast,
simple, but not shared across multiple instances. Distributed cache (e.g. Redis, SQL
Server, NCache) is shared among instances, supports scale out. Use caching of
responses or data. Consider expiration, eviction, cache invalidation.

42. How would you handle throttling / rate limiting?


Answer: Use middleware or use third-party libraries (e.g. AspNetCoreRateLimit).
Rate limit per user/IP. Use sliding window or fixed window counters. Store counters
in distributed storage if multiple instances. Provide proper HTTP status codes (429
Too Many Requests), also headers telling when next allowed.

43. Explain how to implement response caching, and what its pitfalls are.
Answer: Use ResponseCaching middleware, or set proper cache headers
(Cache-Control, ETag, LastModified). Pitfalls: cache sensitive data, caching private
data, stale data, cache invalidation, varying by user or headers needs Vary header,
ensuring you don’t cache error responses incorrectly.

44. What are health checks and how do you configure them?
Answer: Health checks are endpoints that let external monitoring tools check if
service is alive and ready. [Link] Core provides
[Link]. Configure checks (DB
connectivity, external services etc.), map to endpoints (e.g. /health), maybe
liveness and readiness probes in container/orchestration.

45. How to enable logging and what are best practices?


Answer: Use built-in logging abstractions (ILogger<T>), configure providers
(Console, File, Application Insights, Serilog, NLog). Best practices: use proper log
levels (Trace, Debug, Information, Warning, Error, Critical), avoid expensive
operations in logs, log context, correlation IDs, structured logging, centralize logs
(ELK, Splunk etc.), avoid logging sensitive data.

46. What is Distributed Tracing and how to implement in [Link] Core?


Answer: Distributed tracing allows tracing a request as it travels through
microservices or distributed components. Use tools like OpenTelemetry, Jaeger,
Zipkin, or Application Insights. Instrument code (automatic or manual), propagate
context (trace IDs, spans) across HTTP / gRPC / message queues.

47. How do you ensure high availability and zero-downtime deployment for Web
APIs?
Answer: Use load balancing, blue-green or canary deployments, container
orchestration (Kubernetes), health checks, rolling updates, versioning so new
changes don’t break existing clients, database migrations with backward compatible
changes.

48. What strategies exist for scaling out [Link] Core Web APIs?
Answer: Horizontal scaling (multiple instances behind load balancer),
containerization, microservices; vertical scaling if necessary; optimizing code;
caching; offload heavy tasks; use a CDN; partitioning/sharding; use of async; reduce
contention; reduce blocking.

49. How do you measure performance? Tooling & metrics you would use.
Answer: Use profiling tools (dotTrace, Visual Studio Profiler), built-in diagnostics
(Event Tracing for Windows, .NET counters), Application Insights, OpenTelemetry
metrics, logging timings, custom middleware to measure request durations,
monitoring CPU/memory, garbage collection, thread pool, etc.

50. What is the impact of garbage collection on Web API performance? How do
you tune it?
Answer: GC pauses (for large objects, Gen2 collections) can affect throughput and
latency. Use proper sizing of objects, avoid large object allocations frequently, reuse
memory, reduce allocations, possibly configure server GC, tune GCSettings,
monitor with diagnostic tools.

Asynchronous, Streaming & IO


51. How does async / await work under the hood in C#?
Answer: Compiler transforms async methods into state machines. await causes
the method to return to its caller, resume later when the awaited Task completes.
Synchronization context might be involved (in UI apps), but Web APIs typically use
thread pool. Exception handling is captured and re-thrown from await.

52. How do you stream large files through a Web API without loading into
memory?
Answer: Use streaming (e.g. returning FileStreamResult or stream content),
PushStreamContent / StreamContent (older), or use chunked transfer. Use
async streams, avoid buffering entire content in memory. Use
IAsyncEnumerable<T> for streaming data.

53. What is HTTP/2 support in [Link] Core, and how can you enable it? What are
its benefits?
Answer: [Link] Core supports HTTP/2 with Kestrel (provided OS supports).
Benefits: multiplexing, lower latency, header compression, server push. To enable:
configure Kestrel or reverse proxy, ensure TLS, proper settings in
UseKestrel(options => { [Link](...)
}) etc.

54. How do you handle chunked uploads or multipart/form-data uploads?


Answer: For multipart, use IFormFile in controller, stream to storage. For very
large uploads consider streaming directly (e.g. via request body stream), limit sizes,
validate parts. For chunked uploads, accept parts (metadata), assemble on server,
possibly with resumable upload logic.

55. What are I/O completion ports and how do they affect [Link] Core
performance?
Answer: I/O completion ports are OS-level mechanism for efficient asynchronous
I/O on Windows. .NET uses asynchronous file and socket I/O which ultimately uses
I/O completion ports, non-blocking operations. Efficient I/O helps scale to many
concurrent requests without blocking threads.

56. Explain backpressure and how you might implement it in a Web API scenario
(e.g. streaming logs, server push).
Answer: Backpressure is control of data flow to prevent fast producers
overwhelming slower consumers. In Web API, using streaming endpoints,
WebSockets, gRPC, using buffers, flow control. Use reactive streams, limit buffer
sizes, ensure clients have ability to slow down, e.g. via async enumerables,
channels.

API Design & Best Practices


57. What are DTOs? Why use them, and how do you map between domain entities
and DTOs?
Answer: DTO = Data Transfer Object, shape data for API (avoid exposing domain
entity internals, limit data sent, control serialization). Use mapping tools
(AutoMapper) or manual mapping. Also helps for versioning and decoupling domain
from API contract.

58. What are resource naming best practices for REST APIs?
Answer: Use nouns, plural resources (/users, not /getUser), hierarchy in paths
for relationships, avoid including verbs in URLs (use HTTP method), consistent
casing (e.g. kebab-case or camelCase), versioning, support filtering, pagination,
sorting via query parameters.

59. How to handle pagination, filtering, sorting in Web APIs?


Answer: Accept query parameters (page, pageSize, sort, order, filter criteria). Use
data structures for filtering. For efficiency, only fetch required fields (projection).
Return metadata (total items, total pages etc.). Avoid returning giant payloads.

60. Explain HATEOAS and whether it’s worth implementing.


Answer: HATEOAS = Hypermedia as the Engine of Application State. Means
responses include links to related resources, actions. Helps clients discover API.
Adds complexity. Worth if API is public, or evolves often, or you want high
discoverability, or multiple clients. For simpler internal APIs may be overkill.

61. What are status codes you should use, and when? Common mistakes.
Answer: 200 OK for success, 201 Created for resource creation, 204 No Content
when action succeeded but no body, 400 Bad Request for invalid client request, 401
Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 415 Unsupported Media
Type, 500 Internal Server Error, etc. Mistakes: over-using 200 for errors, exposing
internal details in error responses, mixing up 401 vs 403.

62. How do you design error responses / error handling consistent across API?
Answer: Define a standard error response model (error code, message, details).
Use middleware or filters to catch unhandled exceptions and wrap them into error
responses. Do not leak stack traces. Differentiate between client errors and server
errors.

63. What’s the best way to document a Web API?


Answer: Use OpenAPI / Swagger (Swashbuckle or NSwag), generate specs,
include examples, version docs, possibly use XML comments, annotate
controllers/actions. Provide a UI (Swagger UI). Optionally use tools like API portals,
Postman collections etc.

64. How do you support multiple content types (e.g. JSON, XML) and client
preferences?
Answer: Use content negotiation built into [Link] Core; configure formatters
(AddXmlSerializerFormatters etc.), examine Accept header. If unsupported, return
406 Not Acceptable. Possibly control default format or fallback.

65. What considerations are there for API consumer version deprecation?
Answer: Communicate ahead via documentation or headers (e.g. Deprecation
header), maintain multiple versions, provide migration guide, schedule removal, log
usage of deprecated endpoints, possibly route deprecated versions to alternate
implementations.

66. What is idempotency and why is it important for Web APIs? How to implement
it?
Answer: Idempotency means making same request multiple times has same effect
(especially for methods like PUT, DELETE). Useful to avoid duplication (e.g. retries).
Implement by using PUT for updates, using idempotency keys for POST requests
(client provides unique key to identify operation), check for duplicate operations
server-side.

67. How would you design rate and quota limits per client or per resource?
Answer: Use API Gateway (or custom middleware) to track quotas (calls per time
period), store counts in distributed store, enforce limits, return proper response (e.g.
429), include headers (Retry-After), differentiate clients via API keys or tokens.

68. How to version DTOs or schema of responses without breaking clients?


Answer: Use versioning at API level; or support multiple DTO versions; use
optional/new fields; deprecate old fields; avoid changing semantics of existing fields;
use feature flags; serve both new and old shapes in parallel where needed.

69. Explain how localization (i.e. multiple languages) might be supported in a Web
API.
Answer: Accept locale info via header or query, use resource files or databases for
localized strings/messages, for error messages etc. Possibly for content. For
formatting (dates, numbers) respect culture info. Be cautious about exposing
language hashed data.

70. How do you handle Ids vs GUIDs vs integer PKs in your APIs?
Answer: Integers are simple, small. GUIDs more unique, less guessable, avoid
collisions. Alternatively use UUIDs, or even more complex IDs (e.g. snowflake,
ULID). Decide for public APIs (avoid exposing sequential IDs), for
routing/friendliness. Also guard performance (indexes), storage size.

Microservices, Distributed Systems & Integration


71. How do you integrate microservices using Web APIs? What communication
mechanisms?
Answer: Via HTTP/REST APIs, gRPC, message queues or event buses
(RabbitMQ, Kafka), or service mesh. For synchronous interactions, REST or gRPC;
for asynchronous, events/messages. Use patterns like Circuit Breaker, Retry,
Bulkhead for resilience.

72. What patterns help make microservice communication resilient?


Answer: Retry pattern, Circuit Breaker, Bulkhead, Timeout, Fall-back, Retry with
exponential back-off, Idempotency, back‐pressure.

73. What is the API Gateway pattern? What are the trade-offs?
Answer: Gateway sits in front of microservices, handles authentication, routing, rate
limiting, aggregation, etc. Pros: simplifies clients, centralizes cross-cutting concerns.
Cons: can become a bottleneck, single point of failure, extra latency, complexity.

74. Explain how you might implement distributed caching.


Answer: Use a shared cache store like Redis or Memcached, ensure consistency,
invalidation logic, versioning; handle cache expiration; consider cache stampede
(lock/refresh), maybe use coalescing, use local cache + fallback to distributed cache.
75. What is eventual consistency and how to handle it?
Answer: In distributed systems, immediate consistency may not be feasible.
Eventual consistency means data will converge over time. To handle: design
operations that tolerate stale reads, use event driven updates, design business logic
to be concurrency-aware, compensate for conflicts, maybe use versioning or vector
clocks.

76. How do you ensure transactional integrity across multiple services?


Answer: Use Saga pattern (either orchestrated or choreographed), outbox pattern,
idempotency, compensating transactions. Possibly use distributed transaction
coordinators (though heavy and limited).

77. What is the outbox pattern?


Answer: Ensures reliable event publication in a transactional system: changes to
data + record of events in the same database transaction. A separate process reads
outbox table and publishes events to message broker. Prevents lost events in face of
failures.

78. How do you deploy and manage API microservices?


Answer: Containerization (Docker), orchestration (Kubernetes, ECS etc.), CI/CD
pipelines, versioned deployments (blue/green, canary), service discovery,
configuration management, monitoring, logging, tracing.

79. What is service discovery and how to implement it?


Answer: Service discovery allows services to locate each other dynamically (in
dynamic environments). Use DNS, or a registry service (Consul, Eureka), or built-in
in Kubernetes.

80. How do you handle contract testing or API schema testing in microservices?
Answer: Use tools like Pact for consumer-driven contract testing. Maintain API
schemas (OpenAPI), enforce breaking changes etc. Integration tests to validate
contracts.

Advanced C#, .NET Core Specifics


81. What are value tasks vs tasks in C#? When to use ValueTask<T>?
Answer: Task<T> always allocates object; ValueTask<T> can avoid allocation
when result is already known, or reused. But using ValueTask has trade-offs:
cannot be awaited multiple times, performance when misused is worse. Use for
highly performance sensitive scenarios.

82. What is Span<T>, Memory<T>, and how are they relevant in Web APIs?
Answer: Span and Memory types allow safe, efficient handling of slices of memory,
stack vs heap, non-allocating operations. Useful for parsing, high throughput
scenarios, minimizing allocations, working with buffers (e.g. JSON, binary data).

83. Explain garbage collector modes, server GC vs workstation GC.


Answer: Workstation GC is for desktop / low environments, one thread for GC
collections. Server GC optimized for server usage: multiple threads for parallel GC,
large heap, better throughput. Can be configured in runtime config.

84. What’s the difference between IAsyncEnumerable<T> and IEnumerable<T>?


Answer: IAsyncEnumerable<T> supports asynchronous streaming of elements
(e.g. from database or external source), allowing await foreach. Useful for APIs
that return large data or stream over time. IEnumerable<T> synchronous.

85. What are value types vs reference types and how does boxing/unboxing affect
performance?
Answer: Value types allocated in stack (or inline), reference types are on heap.
Boxing (value type to object) causes allocation, possible performance hit. Unboxing
extracts underlying value. Avoid boxing/unboxing in hot paths.

86. How to handle memory leaks in .NET Core? What tools to find leaks?
Answer: Memory leaks often via event handlers, static references, unreleased
IDisposable items (streams, DbContexts), too much caching. Use tools like
dotMemory, Visual Studio Diagnostic Tools, PerfView, GC collection logs. Use proper
Dispose, using statements, weak references, etc.

87. What is IHostedService and how do you use it?


Answer: IHostedService represents a background service in [Link] Core
(hosted inside the web host). Use for background tasks (e.g. scheduled jobs). You
implement StartAsync, StopAsync. Can also use BackgroundService base
class.

88. What are Endpoint Filters (in minimal APIs)?


Answer: Filters that run before or after endpoints in minimal APIs; allow cross-
cutting concerns (validation, authorization, logging etc.) in minimal API style.

89. Explain Difference between ControllerBase vs Controller in [Link]


Core.
Answer: Controller includes view support (MVC view rendering) plus API
support; ControllerBase is more minimal, only API features (no view support),
lighter. For APIs we typically use ControllerBase + [ApiController].

90. What does [ApiController] attribute do?


Answer: Enables API-specific behaviors: automatic model validation (400
responses), binding source inference (e.g. [FromBody], [FromQuery]), automatic
HTTP 400 on bad model, attribute routing requirement, problem details behavior etc.

Testing & DevOps


91. How do you write unit tests for Web API controllers? What to mock?
Answer: Test controllers in isolation: mock dependencies (services, repositories) via
DI, use in-memory stores. Use test frameworks like xUnit / MSTest / NUnit. Assert
action results, status codes, content.

92. How do you write integration tests for Web API?


Answer: Use TestServer / WebApplicationFactory (in [Link] Core) to host API in
memory, send HTTP requests, test end-to-end. Use real or in-memory database, use
configuration overriding.

93. Explain mocking strategies. What are the trade-offs?


Answer: Mock dependencies (services, data layers); trade-offs: mocks reduce
coupling and speed tests, but over-mocking can weaken confidence; use real
dependencies where feasible; keep mocks maintainable; prefer interfaces.

94. How do you set up CI/CD for Web API projects?


Answer: Use build pipelines (GitHub Actions, Azure DevOps, Jenkins etc.), run
tests, code analysis, static code checks, build containers/images, push to registry,
deploy via deployment pipelines to staging and production.

95. How do you deploy to Docker / Kubernetes? What considerations for Web API?
Answer: Dockerize the app, write Dockerfile, ensure configuration via env vars, set
correct ports, health checks. In Kubernetes: define Deployment, Service, Ingress,
liveness/readiness probes, resource requests/limits, secrets management.

96. How do you deal with migrations in a zero-downtime deployment scenario?


Answer: Use backward compatible schema changes (add columns nullable, avoid
dropping columns), maybe dual writes temporarily, ensure old code continues to
work with new schema, run migrations in deployment before swapping traffic, canary
or blue/green deployments.

97. What monitoring / alerting would you set up for production Web APIs?
Answer: Track request rates, latency, error rates, CPU/memory usage,
dependencies (database, external APIs) availability. Use metrics + dashboards
(Grafana, Application Insights), set thresholds and alerts.

98. How do you perform load testing and stress testing of Web API?
Answer: Use tools (e.g. JMeter, k6, Locust), simulate realistic traffic, measure
metrics under load (throughput, latency, errors), test scaling, test data size,
concurrency, simulate failure of dependencies.

99. What is blue/green deployment, and can you give a scenario in which you'd
use it for Web API?
Answer: Two nearly identical environments (blue and green), deploy new version to
idle one, test, then switch traffic. Use in Web APIs to avoid downtime when deploying
new version, roll back quickly if problems.

100. How do you ensure database migrations or seed data do not


compromise data in production?
Answer: Use backups, scripts, verify in staging, run migrations incrementally,
monitor, possibly use feature flags, avoid destructive changes, test rollback
strategies.

Advanced Topics / Edge Cases


101. How to handle circular references in JSON serialization?
Answer: Use attributes or settings: e.g. in [Link], configure
[Link] or ignore loops; in [Link] use
[JsonIgnore], PreserveReferencesHandling, or manage DTOs that break
the cycles.

102. What’s the difference between [Link] vs


[Link]? Which to use and why?
Answer: [Link] is built in, faster for many scenarios, lower memory
footprint; but fewer features (less mature, less flexible). [Link] has
more popularity, more features (flexible converters etc.). Use built-in unless you need
advanced features.

103. How do you implement custom JSON converters / formatters?


Answer: In [Link]: implement JsonConverter<T>; register via options
(AddJsonOptions). For custom media type formatters (older). Use in [Link]
Core via options.

104. Explain CancellationToken in Web API. How do you use it?


Answer: CancellationToken allows canceling ongoing async operations (e.g. by
client disconnect or request timeout). In controller actions pass
CancellationToken parameter; in service methods respect cancellation; for long
running tasks check for cancellation; propagate cancellation upstream.

105. How do you limit payload size / request size to protect from large
requests?
Answer: Configure Kestrel or server/proxy limits. The RequestSizeLimit
attribute, or configure through options. For file uploads via IFormFile, set limits.
Use streaming and multipart. Also validate content length etc.

106. What is binding source attributes (FromBody, FromQuery, FromRoute,


FromForm)? Differences?
Answer: These attributes tell model binding where to get data. FromBody from
request body; FromQuery from query string; FromRoute from route values;
FromForm from form data. For complex types, default binding sources differ.
ApiController infers some automatically.

107. How to handle optional parameters, default values and model binding
constraints?
Answer: Use nullable types or default values in action method signature; use
[Required], [Range], [StringLength], custom model binder or validation
attributes. Use route constraints in routing.

108. How do you support cancellation of requests when client disconnects?


Answer: [Link] Core propagates cancellation via
[Link] token; pass it to async operations. If client
disconnects, cancellation token triggers, can stop processing further.

109. What is gRPC and how is it supported in .NET Core? When to choose
gRPC vs Web API?
Answer: gRPC is high performance, strongly typed RPC framework using HTTP/2,
protocol buffers. In .NET Core, there is built-in support. Use when you need low
latency, inter-service communication, binary protocols, streaming. Web API is better
for more general HTTP/REST, compatibility, broader client support.
110. How to handle versioning with backwards-compatible database changes
(e.g. renaming columns, splitting tables)?
Answer: Use shadow columns for renames (keep old, add new, migrate data),
deprecate old fields, mapping in DB views, avoid dropping until no clients use old
fields; for splitting tables maybe views; ensure schema supports both versions;
migrate gradually.

111. What are "problem details" (RFC 7807) and how do you implement them
in [Link] Core?
Answer: Problem Details is a standard for representing HTTP API errors in JSON in
a consistent shape. [Link] Core supports it via ProblemDetails class. Use in
exception filters or middleware.

112. How to implement GraphQL or OData endpoints in [Link] Core Web


API?
Answer: For OData: use [Link], set up OData routing,
controllers etc. For GraphQL: use [Link] or Hot Chocolate; define schema,
types, resolvers; consider performance, caching.

113. What is SignalR, and how would you integrate real-time events with a
Web API?
Answer: SignalR provides real-time communication (web sockets, server-sent
events fallback). To integrate, host SignalR hubs in the same server, or separate.
Clients subscribe; API or background services send messages. Use for live
notifications etc.

114. Explain cookies vs tokens for authentication. What are pros and cons?
Answer: Cookies easier for browser apps (automatic inclusion), can be vulnerable
to CSRF; tokens (JWT) more flexible, mobile friendly, stateless; tokens require
header inclusion, storage (localStorage etc.) (risk XSS). Cookies can support secure
and HttpOnly etc.

115. What is a middleware ordering issue that could cause subtle bugs?
Answer: Example: placing UseRouting after authentication; if
UseAuthentication comes after endpoint mapping, authentication won't apply. Or
static files before authorization, or error handling placed after endpoints so
exceptions aren’t caught. The order of CORS, authentication, authorization matters.

Real-World Scenario / Case Questions


116. You have an API that sometimes hangs or is very slow under load. How
do you diagnose and fix it?
Answer: Use profiling / tracing, check logs, monitor metrics. Look for slow database
queries (N+1), blocking calls, thread pool starvation, resource contention, GC
pauses, memory pressure. Fix by optimizing queries, using async, caching, scaling
out, improving hardware or configuration, increasing thread pool, avoiding blocking in
middleware.

117. You’re building a public API used by many versions of clients. New
feature requires modifying the API. How to do it without breaking existing
clients?
Answer: Use versioning. Introduce new endpoint or new version (for example v2).
Keep old endpoints intact. Use optional fields. Deprecate old API, provide migration
path. Document changes. Possibly use feature flags.

118. How would you migrate a monolithic Web API to microservices?


Answer: Identify bounded contexts / modules, split by domain, extract services
gradually. Use façade / API Gateway to provide unified API during migration. Move
data carefully, possibly shared database first, then separate DBs. Decide
communication patterns, cross-service transactions, resilience. Monitoring and
logging centralization.

119. Suppose one of your Web APIs must call multiple downstream services
and aggregate results (fan-out). How do you make it performant and resilient?
Answer: Use asynchronous calls in parallel; set timeouts; implement Circuit Breaker
/ fallback; consider caching or batching; handle partial failures gracefully; possibly
use data streaming; consider controlling concurrency; avoid blocking.

120. You detect that the database is becoming a performance bottleneck.


What are possible strategies?
Answer: Index optimization; read replicas; caching; sharding; partitioning; using a
different database for read operations; denormalization; use NoSQL for certain data;
offload reporting queries; use connection pooling; use faster DB engine; optimize
SQL queries.

Platform and Environment


121. How do you build cross-platform Web API (Windows / Linux / Docker)?
Any differences?
Answer: Use .NET Core or .NET 5/6+, code is cross platform. For platform-specific
concerns (file paths, line endings, environment variables), use abstraction. In Docker,
ensure base image, environment settings. Ensure performance differences (e.g. file
system).

122. How do you configure environment-specific settings (development,


staging, production)?
Answer: Use ASPNETCORE_ENVIRONMENT variable, appsettings.
{Environment}.json, environment variables override, secret stores, conditional service
registration, logging levels per environment.

123. How do you handle secrets in Azure (or AWS / GCP)?


Answer: Use Azure Key Vault, AWS Secrets Manager, GCP Secret Manager. Store
secrets securely, access from code via managed identity or secure credentials. Do
not store secrets in source code or config files.

124. What containerization best practices for Web API?


Answer: Small base image, multi-stage builds, expose only necessary ports, health
probes, resource limits, environment configuration via env vars, logging to
stdout/stderr, avoid storing state in container.
125. What is Serverless (e.g. Azure Functions) vs Web API, and when to use
each?
Answer: Serverless runs on demand, scales automatically, often pay per usage,
good for event-driven APIs or small tasks. Web API (hosted) is always on, more
control, better for continuous high traffic, more complex routing, middleware etc.

126. How do you monitor and log in containerized environment (e.g.


Kubernetes)?
Answer: Use side-car logging, centralized logging (ELK, EFK, Splunk), metrics via
Prometheus, use liveness and readiness probes. Use tracing instrumentation. Use
structured logs.

127. What is side-loading vs layering in Docker images?


Answer: Layering means structuring Dockerfile so that lower layers don’t change
often (e.g. restore NuGet first, then build), caching. Side-loading is less standard
term; maybe copying artifacts rather than rebuilding.

128. How do you configure [Link] Core to run inside a container behind
reverse proxy (e.g. NGINX)?
Answer: Trust proxy headers (UseForwardedHeaders), configure forwarded
headers options, ensure proper environment variables, HTTPS termination at proxy,
Kestrel listening on internal port, set ASPNETCORE_URLS, configure ports.

Practical Implementation / Coding


129. How would you implement a generic repository interface?
Answer: Define interface like IRepository<T> with methods like Task<T>
GetAsync, Task<IEnumerable<T>> GetAllAsync, Task AddAsync, Task
Update, Task Delete. Implement using EF Core context; handle saving. Possibly
have generic base and specific PIs if needed.

130. Write a middleware component that logs request and response times.
Answer: Implement IMiddleware or inline in Use(...) that captures
Stopwatch, calls next(), measures elapsed time, logs along with path, method,
status code.

131. How to implement custom validation attribute?


Answer: Subclass ValidationAttribute, override IsValid, possibly use
ValidationContext, create attribute, apply to model properties. Or use
IValidatableObject on model.

132. How to implement a retry policy using Polly in [Link] Core?


Answer: Add Polly package; define resilience policies (retry, wait, circuit breaker
etc.) in ConfigureServices, for example when configuring HTTP clients via
[Link](...).AddTransientHttpErrorPolicy(p =>
[Link](...)). Use in outgoing HTTP calls.
Write code snippet for streaming JSON result using IAsyncEnumerable<T>.
Answer:

[HttpGet]
public async IAsyncEnumerable<MyDto>
GetStreamed([EnumeratorCancellation] CancellationToken ct)
{
await foreach (var item in
_service.GetItemsAsync().WithCancellation(ct))
{
yield return item;
}
}

133.

Show how to configure [Link] / [Link] for minimal API or controller-


based API.
Answer: In .NET 6+:

var builder = [Link](args);


[Link]();
[Link]();
[Link]();
var app = [Link]();
if ([Link]()) { [Link]();
[Link](); }
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();

134.
135. Implement rate limiting middleware using in-memory store.
Answer: Keep a dictionary keyed by client (IP or API key), store timestamps of
requests, count within window, reject if exceeded. Use sliding or fixed window. For
production use distributed store (Redis) for shared state.

136. How to implement a custom exception filter?


Answer: Create class inheriting ExceptionFilterAttribute, override
OnException or OnExceptionAsync, set [Link] to a custom
ObjectResult / ProblemDetails etc., set status code. Register globally or per
controller via filter collection.
137. Write code for bulk insert with EF Core.
Answer: There is no built-in bulk insert; options: loop insert with batching, or use
third-party libraries (e.g. [Link]), or use raw SQL / stored
procedure.

138. How to implement file upload and virus scan in Web API?
Answer: Accept file via IFormFile, store temporarily, scan (using external antivirus
API or library), if safe store permanently. Validate file size/type, handle as stream,
use streaming if large, avoid memory exhaustion.

139. How to support both sync and streaming response (e.g. partial content
for downloads)?
Answer: Use FileStreamResult, support range requests (set headers, process
Range header). Implement streaming and enabling partial content via Response
with status 206, etc.

140. How to manage object graph mapping when domain objects have
nested objects / child collections (for PATCH)?
Answer: Use DTOs representing only changeable fields, use JSON Patch
(JsonPatchDocument) or custom patch models. Ensure patch operations targeted.
Use AutoMapper with .ProjectTo or manual mapping.

Cross-Cutting, Tools & Libraries


141. What is AutoMapper? Pros and cons.
Answer: AutoMapper helps map between domain models and DTOs automatically,
reduces boilerplate. Pros: reduces manual code, maintainability. Cons: hidden
mapping, sometimes unclear performance, sometimes problematic for complex
mapping, debugging.

142. What is Serilog/NLog etc, and how do you configure structured


logging?
Answer: Logging libraries supporting structured (key/value) logs, sinks to file, DB,
streaming etc. Configure via UseSerilog() in Program, sinks, output templates.
Use properties for context (e.g. [Link]).

143. What is Swagger / OpenAPI and how to generate it in .NET Core?


Answer: OpenAPI is a specification for RESTful APIs. Use Swashbuckle or NSwag
in [Link] Core: [Link](), annotate controllers/actions,
generate UI via [Link](), [Link](). Use XML comments
if needed, set up examples.

144. How to use HTTP client factories in .NET Core and why?
Answer: Use IHttpClientFactory ([Link]) to configure
named or typed clients; manages lifetime of HttpClient handlers, avoids socket
exhaustion, allows policies (retry, timeout), central config.
145. What is gRPC vs REST, and when to use each? (This is similar to earlier
but more depth.)

146. What is OpenTelemetry and how to instrument a .NET Core Web API
with it?
Answer: OpenTelemetry is a set of standards and libraries for telemetry (tracing,
metrics, logging). In .NET Core: install OpenTelemetry packages, configure in
[Link], add instrumentation for [Link] Core, HTTP client, EF Core etc.,
export to backends (Jaeger, Zipkin, etc.).

147. What are the benefits of using Content Delivery Networks (CDN) with
Web APIs for static content / assets?
Answer: Reduces latency for clients, lowers load on API servers, caches assets
closer to edge, better performance globally. Web API generally not for static content
but CDNs complementary.

148. What is Cross cutting concerns, and how do you handle them (e.g.
logging, validation, caching, authorization)?
Answer: Use middleware, filters, attributes, policies, DI to inject behaviors. Use
interceptors or aspects (AOP) where necessary.

149. How do you ensure thread safety in your Web API services?
Answer: Avoid shared mutable static state; when using singletons ensure internal
state is thread safe; avoid race conditions; use locking or concurrency safe
collections; immutable types where possible.

150. How to monitor memory usage and diagnose memory leaks in


production?
Answer: Use diagnostic tools (dotnet counters, Prometheus + metrics, memory
dumps, GC logs), monitor heap sizes, track objects retained across GCs, analyze
with PerfView or Visual Studio. Use logging of memory metrics.

Additional Advanced / Corner / Best Practice Questions


151. What is the role of ProblemDetails in HTTP APIs according to RFC
7807? (expand on earlier)
Answer: Provides standardized schema for error responses (type, title, status,
detail, instance), helps clients understand error. Use ProblemDetails class; in
exception middleware or filters return ProblemDetails.

152. How would you support PATCH operations? What are the trade-offs?
Answer: Use JSON Patch (JsonPatchDocument), or partial update DTOs. Trade-
offs: complexity, possibly more brittle, need to validate operations, handle
concurrency, and ensure partial updates don't violate invariants.

153. What is API client generation and how might you support it (e.g.
TypeScript or C# clients)?
Answer: Use OpenAPI spec to generate client SDKs (via NSwag, AutoRest,
Swagger Codegen). Helps consumers integrate. Need to maintain spec, versioning,
and ensure generated client is correct.

154. How do you handle overlapping or conflicting route templates in


[Link] Core?
Answer: Be explicit in attribute routing, avoid ambiguous routes, use route
constraints, prioritize specific routes over less specific, test route matching, inspect
route table.

155. What is binding to custom model binder? When do you need one?
Answer: Custom model binders allow you to define how parameters are bound from
request (e.g. custom formats, complex binding, multi-source). Use when default
binding insufficient (complex query string formats, custom serialization, etc.).

156. Explain how to use IFormFile vs direct stream vs buffered vs


unbuffered, and performance implications.
Answer: IFormFile typically buffers small files in memory or temp file. For large
uploads, use streaming to avoid buffering and memory pressure. Unbuffered
streaming or chunked. Also configure upload limits.

157. What is hystrix (or similar circuits) and how to emulate in .NET?
Answer: Hystrix (from Netflix) provides circuit breaker, fallback etc. In .NET use
Polly to implement circuit breaker, fallback, timeouts etc.

158. How to handle culture / time zones in APIs?


Answer: Always store dates in UTC; accept time zone or offset or use ISO formats;
map to local zones when needed; validate culture in requests; use CultureInfo for
parsing/formatting; avoid culture-specific logic unless required.

159. How to deal with serialization of enums, nullables, default values etc.
Answer: Use attributes or settings (StringEnumConverter /
JsonStringEnumConverter), how to output null values (IgnoreNullValues or
DefaultIgnoreCondition), default values, configure naming policies (camelCase
/ PascalCase), control JSON naming, etc.

160. What are implicit/explicit operators in C# and when might they be used
in DTO/domain model mapping?
Answer: Define conversion operators implicit operator T(...) or
explicit for converting between types. Could be used between domain
types/DTOs but overuse can hurt readability. Use with care.

Cloud, Integration, Message Brokers


161. How do you integrate Azure Functions / AWS Lambda as part of your
Web API ecosystem?
Answer: Offload certain lightweight or event-driven tasks to serverless. Use them
behind triggers (HTTP, queue, event grid), integrate via HTTP or messages; design
so that APIs call them, or they publish events consumed by API or other services.

162. How do you use message brokers (e.g. RabbitMQ, Kafka) together with
Web API?
Answer: Use for asynchronous communication: commands, events. API publishes
messages/events, services subscribe. Use durable queues, ensure idempotency,
retry, error queues, schema versioning, monitoring.

163. What is the outbox pattern? (already mentioned)


Answer: Ensures that events/messages are persisted with state changes in same
transaction (so no events are lost). Then a separate process or service reads outbox
table and sends messages.

164. How to handle API requests from mobile / offline clients?


Answer: Consider Delta sync (change sets), caching on client, offline queues,
conflict resolution, perhaps versioning, maybe local storage, exponential backoff etc.

165. What strategies do you use for backward compatibility in database


changes? (similar earlier)

166. How do you design secure service-to-service communication?


Answer: Use mutual TLS or token-based service accounts, limited scopes, encrypt
data in transit, validate certificates, use identity providers, possibly mutual
authentication.

167. What is TLS renegotiation or certificate pinning, and is it relevant?


Answer: Certificate pinning ensures client only trusts specific certificates, reduces
MITM risk. TLS renegotiation concerns session reuse, security. For APIs, certificate
management matters, pinning maybe for clients.

168. How would you migrate a database while multiple service versions are
live?
Answer: Use backward compatible schema, maybe add new columns, views,
maintain old behavior, gradually migrate clients, then remove old schema parts once
no clients use them.

169. How would you do blue / green or canary deployment of Web API in
cloud environment? (similar earlier)

170. How to ensure idempotence and to avoid duplicate processing in case


of retries in distributed systems?
Answer: Use idempotency keys, check before processing; use unique constraints;
store processed request IDs; use message deduplication in broker, use API Gateway
that handles retries carefully.

Deep Dive / “Tricky” Questions


171. What is the difference between Hot reload vs dotnet watch vs live
updating?
Answer: dotnet watch reruns the app when code changes; hot reload applies
code changes without restarting, preserving app state. In Web APIs may use hot
reload in dev; in prod, deployments.

172. Explain how links between .NET Core runtime, CLR, JIT, RyuJIT, JIT
tiers work.
Answer: .NET Core uses CoreCLR, which includes JIT (RyuJIT) to compile IL to
native or sometimes Ahead-of-Time compilation (ReadyToRun). There is Tiered
compilation (quick inner loop compilation followed by optimized version).

173. What is ReadyToRun (R2R), and how does it affect startup and runtime
behavior?
Answer: ReadyToRun images are pre-compiled native code versions of IL;
improves startup performance by avoiding some JIT overhead, at cost of larger
binaries; might affect inlining etc.

174. What is cross-gen / Cross-gen2, and when do you use it?

175. Explain trimming (IL Linker) in .NET and its implications for Web API.
Answer: Trimming removes unused IL to reduce size in deployment. Risk: reflection
usage may break if code needed via reflection is trimmed. Need to annotate or
configure to preserve types. Usually used for client or publishing.

176. How does AOT (Ahead-of-Time) compilation work in .NET? Benefits and
limitations.
Answer: AOT compiles to native code ahead of runtime; reduces startup latency;
may restrict some runtime features (reflection, dynamic code). Currently used in
specific scenarios (.NET Native, Native AOT).

177. What is “GC Latency Mode”, what are “pause times”, and how to
minimize them?
Answer: In .NET you can configure GC modes (e.g. Server GC), background GC,
etc. Pause times (stop-the-world) occur during Gen0/1/Gen2 collections. Reduce
allocations, prefer small objects, reuse memory, avoid large LOH allocations, tune
GC settings.

178. What are Span<T> and Memory<T> types and what constraints do they
have (stack vs heap)? (similar to earlier)

179. Explain how the JIT does inlining; when is inlining possible or
prevented.

180. What is Tiered compilation and how does it affect JIT performance?

Current / Trending Topics


181. What is .NET 8 / .NET 9 bringing for Web API? (or latest version
features)
Answer: (As of 2025) .NET continues improving performance, minimal APIs,
endpoint filters, improvements to source generators, enhancements to HTTP stack,
better JSON / [Link] features, more AOT/native capabilities, improved
cloud / container support.

182. What is minimal hosting model vs generic host?

183. What is rate limiting built into .NET? Are there built-in APIs now?
184. What is Hot Reload for .NET in Web API development?

185. What are source generators, and how might they help in Web API and
DTO generation or mapping?

186. What is the future of Web API regarding GraphQL, gRPC, or OData
in .NET ecosystem?

187. How do you use Blazor server / WASM with Web API?

188. How do you ensure Observability (logs, metrics, tracing) across


distributed microservices in .NET?

189. What role does HTTP/3 play, and when might .NET Web APIs support it?

190. What scenarios drive choosing binary serialization (e.g. protobuf) vs


JSON?

Misc / Soft / System & Edge Questions


191. Describe how memory or CPU usage could leak over time in a long-
running Web API and how to prevent it.

192. How do you handle version skew or compatibility when service A


depends on service B which changes?

193. What are the trade-offs of using monolith vs microservices for an API
backend?

194. How do you deal with data consistency, duplication, eventual


consistency in caching?

195. When and how should you use background jobs or queues rather than
executing everything in request pipeline?

196. Explain the CAP theorem in context of building distributed Web APIs.

197. How to implement feature flags/toggles in Web API codebase?

198. When you might prefer to use serverless endpoints vs containerized


Web API?

199. How do you support auditing, logging of changes, versioning of data?

200. What are ethical/security/privacy concerns when exposing Web APIs


(e.g. data exposure, GDPR, PII)?
Advanced .NET Core Web API C#
Interview Questions & Answers

Section 1: .NET Core Fundamentals


1. What is .NET Core, and how does it differ from the .NET Framework?
Answer:
.NET Core is a cross-platform, open-source framework developed by Microsoft for building
modern cloud-based and web applications. Unlike the traditional .NET Framework, which is
Windows-only, .NET Core runs on Windows, Linux, and macOS. It is modular, lightweight,
and optimized for high performance. It supports side-by-side versioning, allowing multiple
versions of .NET Core to coexist on the same machine, which is not possible with .NET
Framework.

2. What is the purpose of the Startup class in a .NET Core Web API project?
Answer:
The Startup class is the entry point for configuring the application. It contains two main
methods:

● ConfigureServices(IServiceCollection services): Used to register


services with the Dependency Injection (DI) container.

● Configure(IApplicationBuilder app, IWebHostEnvironment env):


Used to set up the request processing pipeline using middleware.

3. Explain the difference between .NET Core SDK and Runtime.


Answer:

● SDK (Software Development Kit): Includes everything needed to build and develop
.NET Core applications, including the compiler, libraries, and CLI tools.

● Runtime: Only includes the resources needed to run existing .NET Core
applications, without the build tools.

4. What are the different project types in .NET Core?


Answer:

● Console Applications: For command-line apps.

● Web Applications: [Link] Core MVC apps.

● Web API: For building RESTful services.

● Class Libraries: Reusable components.

● Worker Services: Background services, often used in microservices architectures.


5. How does .NET Core handle cross-platform development?
Answer:
.NET Core is platform-agnostic, thanks to its modular runtime called CoreCLR and a
platform-independent class library (CoreFX). The same code can be compiled and run on
Windows, Linux, or macOS without changes, making deployment and CI/CD pipelines
simpler.

Section 2: Dependency Injection (DI) and Services


6. What is Dependency Injection in .NET Core?
Answer:
Dependency Injection is a design pattern that allows a class to receive its dependencies
from an external source rather than creating them internally. In .NET Core, DI is built-in and
simplifies unit testing, decouples components, and makes code more maintainable.

7. Explain the three service lifetimes in .NET Core DI.


Answer:

● Singleton: A single instance is created and shared throughout the application


lifetime.

● Scoped: A new instance is created per HTTP request.

● Transient: A new instance is created every time it’s requested.

8. How do you register a service in .NET Core DI?


Answer:
You register services in the ConfigureServices method in [Link]:

[Link]<IMyService, MyService>();
[Link]<IMyService, MyService>();
[Link]<IMyService, MyService>();

9. Can you inject services into middleware?


Answer:
Yes, middleware can have services injected via the constructor. However, you should avoid
directly injecting scoped services into middleware constructors because middleware is
singleton by default. Instead, use IServiceProvider or [Link](async (context,
next) => ...).

10. What is the difference between constructor injection and method injection?
Answer:

● Constructor Injection: Dependencies are provided through the constructor,


ensuring immutability and making it clear what the class requires.
● Method Injection: Dependencies are provided as method parameters, useful for
optional or rarely used dependencies.

Section 3: Middleware and Request Pipeline


11. What is middleware in [Link] Core?
Answer:
Middleware is software that is assembled into an application pipeline to handle requests and
responses. Each middleware component can perform operations before and after the next
component in the pipeline executes. Examples include logging, authentication, exception
handling, and routing.

12. Explain the order of middleware execution.


Answer:
Middleware executes in the order it is added in Configure method. The request flows
“down” the pipeline, and the response flows “up” the pipeline. Ordering matters; for example,
authentication should come before authorization middleware.

13. How do you create custom middleware?


Answer:
A custom middleware class must include:

public class MyMiddleware


{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) { _next = next; }

public async Task InvokeAsync(HttpContext context)


{
// Pre-processing
await _next(context);
// Post-processing
}
}

Then register it using [Link]<MyMiddleware>();.

14. Difference between Use, Run, and Map in middleware?


Answer:

● Use: Adds middleware to the pipeline, can call next middleware.

● Run: Adds terminal middleware, does not call next.

● Map: Branches the pipeline for specific path conditions.


15. How is exception handling typically implemented in .NET Core Web API?
Answer:
Exception handling is often implemented using middleware. The built-in middleware
UseExceptionHandler or custom middleware can catch exceptions globally, log them,
and return a structured error response.

Section 4: Routing and Controllers


16. Explain attribute routing in [Link] Core.
Answer:
Attribute routing allows defining routes directly on controllers and action methods using
attributes like [Route("api/[controller]")] and [HttpGet("{id}")]. It provides
more fine-grained control over URL patterns compared to conventional routing.

17. Difference between conventional routing and attribute routing.


Answer:

● Conventional routing: Defined in [Link] or [Link] and


applies globally based on patterns.

● Attribute routing: Defined at the controller/action level with attributes, allowing


precise control over individual endpoints.

18. What is the [ApiController] attribute?


Answer:
The [ApiController] attribute simplifies API development by enabling automatic model
validation, binding source inference, and consistent HTTP 400 responses when the model
state is invalid.

19. Explain model binding in [Link] Core Web API.


Answer:
Model binding maps data from HTTP requests (query strings, route data, form data,
headers, or body) to action method parameters. It reduces manual parsing and improves
readability.

20. How do you handle route constraints?


Answer:
Route constraints limit acceptable route parameter values. Example:
[HttpGet("{id:int}")] ensures id is an integer. Other constraints include
minlength, maxlength, regex, etc.

21. Difference between [FromBody], [FromQuery], and [FromRoute].


Answer:

● [FromBody]: Binds JSON or XML from request body.


● [FromQuery]: Binds data from query string.

● [FromRoute]: Binds data from URL route parameters.

22. How do you version Web APIs in .NET Core?


Answer:
API versioning can be implemented using the
[Link] package. Methods include:

● URL segment: /api/v1/controller

● Query string: /api/controller?api-version=1.0

● HTTP headers: api-version: 1.0

23. What is the purpose of ProducesResponseType?


Answer:
ProducesResponseType documents the possible HTTP responses for an action method.
It helps tools like Swagger generate accurate API documentation.

24. How can you return custom HTTP status codes in Web API?
Answer:
You can use built-in methods such as:

return Ok(data); // 200


return Created(uri, obj); // 201
return NotFound(); // 404
return BadRequest(); // 400
return StatusCode(500); // Custom code

25. Difference between IActionResult and ActionResult<T>.


Answer:

● IActionResult: Can return any type of HTTP response.

● ActionResult<T>: Strongly typed response with additional HTTP status flexibility.

Section 5: Model Validation and Data Annotations


26. How do you validate models in [Link] Core?
Answer:
Models can be validated using data annotations like [Required], [StringLength],
[Range], and [EmailAddress]. The [ApiController] attribute ensures automatic
validation, returning 400 if invalid.
27. How can you create custom validation attributes?
Answer:
Implement ValidationAttribute and override IsValid:

public class CustomEmailAttribute : ValidationAttribute


{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if ([Link]().EndsWith("@[Link]")) return
[Link];
return new ValidationResult("Invalid domain");
}
}

28. What is FluentValidation?


Answer:
FluentValidation is a popular library for building complex, strongly typed validation rules
outside of data annotations. It allows reusable, composable rules with better separation of
concerns.

29. Explain automatic model state validation.


Answer:
With [ApiController], [Link] Core automatically checks [Link]
before executing the action. If invalid, it returns a 400 Bad Request with error details,
avoiding manual checks.

30. Difference between server-side and client-side validation.


Answer:

● Server-side: Validates data on the server, secure and reliable.

● Client-side: Provides instant feedback to users but can be bypassed; it


complements server-side validation.

Section 6: Dependency Injection Advanced Topics


31. How do you inject configuration settings into services?
Answer:
Use IOptions<T>:

[Link]<MySettings>([Link]("MySettings"
));
public class MyService
{
private readonly MySettings _settings;
public MyService(IOptions<MySettings> options) { _settings =
[Link]; }
}

32. Difference between IServiceProvider and DI container.


Answer:

● DI container: Registers and manages service lifetimes.

● IServiceProvider: Resolves services from the container at runtime.

33. How do you inject multiple implementations of an interface?


Answer:
Register multiple services:

[Link]<INotification, EmailNotification>();
[Link]<INotification, SmsNotification>();

Inject IEnumerable<INotification> to access all implementations.

34. How do you use Func<T> and Lazy<T> for DI?


Answer:

● Func<T> allows deferred resolution of a service.

● Lazy<T> delays creation until first access. Both help improve performance for
expensive services.

35. How do you handle circular dependencies?


Answer:
Avoid circular dependencies by refactoring services or using Lazy<T> or factory methods
to break direct dependencies.

Section 7: Entity Framework Core Integration


36. What is Entity Framework Core (EF Core)?
Answer:
EF Core is an ORM for .NET Core that maps database tables to C# objects, simplifying
CRUD operations. It supports LINQ queries, migrations, and multiple database providers
(SQL Server, PostgreSQL, MySQL, SQLite).

37. Difference between EF Core and EF 6.


Answer:
EF Core is lightweight, cross-platform, and optimized for modern applications. EF 6 is
Windows-only, feature-rich, and better for legacy apps. EF Core lacks some EF 6 features
but improves performance and extensibility.

38. Explain DbContext in EF Core.


Answer:
DbContext manages database connections, tracks entity changes, and provides methods
like Add, Update, Remove, and SaveChanges. Each DbContext instance should be scoped
per request.

39. What are migrations in EF Core?


Answer:
Migrations allow versioning of database schema. Commands like Add-Migration and
Update-Database help apply changes incrementally without losing data.

40. Difference between IQueryable and IEnumerable in EF Core.


Answer:

● IQueryable: Executes queries on the database server (deferred execution).

● IEnumerable: Fetches data into memory first (immediate execution).

Section 8: Security
41. How do you implement authentication in .NET Core Web API?
Answer:
Authentication verifies user identity. In .NET Core, you can use:

● JWT (JSON Web Tokens) for stateless token-based auth.

● Cookie-based authentication for web apps.

● IdentityServer4 / OpenIdConnect for OAuth2/OpenID Connect.

42. How do you implement JWT authentication?


Answer:

1. Configure JWT in [Link]:

[Link]([Link])
.AddJwtBearer(options => {
[Link] = new
TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = "YourIssuer",
ValidAudience = "YourAudience",
IssuerSigningKey = new
SymmetricSecurityKey([Link]("SecretKey"))
};
});

2. Use [Authorize] on controllers/actions.

3. Generate JWT in login endpoints with claims.

43. Difference between Authentication and Authorization.


Answer:

● Authentication: Verifies who the user is.

● Authorization: Determines what actions/resources the authenticated user is allowed


to access.

44. How do you protect APIs from CSRF attacks?


Answer:
CSRF is mostly relevant for browser-based requests. Protect APIs using:

● Anti-forgery tokens for forms.

● Using stateless JWT tokens with Authorization header (less vulnerable).

● CORS policies restricting origins.

45. Explain role-based and policy-based authorization.


Answer:

● Role-based: Assign roles to users and restrict actions via


[Authorize(Roles="Admin")].

● Policy-based: Define complex rules with AuthorizationPolicyBuilder and


apply [Authorize(Policy="MyPolicy")].

46. How can you secure sensitive data in Web API?


Answer:

● Use HTTPS for all requests.

● Avoid storing secrets in code; use Azure Key Vault or environment variables.

● Use encryption for sensitive fields in databases.


● Use DataProtection APIs for tokens or passwords.

47. Difference between symmetric and asymmetric encryption in .NET Core.


Answer:

● Symmetric: Same key for encryption/decryption (e.g., AES). Fast but key must be
shared securely.

● Asymmetric: Public/private key pair (e.g., RSA). Slower but allows secure key
exchange and digital signatures.

48. How do you hash passwords in .NET Core?


Answer:
Use PasswordHasher<TUser> from Microsoft Identity:

var hasher = new PasswordHasher<User>();


string hashed = [Link](user, "password123");
var result = [Link](user, hashed,
"password123");

49. How do you implement CORS in .NET Core?


Answer:

[Link](options => {
[Link]("AllowSpecific", builder =>
[Link]("[Link]
.AllowAnyMethod()
.AllowAnyHeader());
});
[Link]("AllowSpecific");

50. How do you prevent SQL Injection in EF Core?


Answer:

● Always use parameterized queries or LINQ.

● Avoid string concatenation in SQL.

● EF Core automatically parameterizes LINQ queries.

Section 9: Logging and Monitoring


51. How is logging implemented in .NET Core?
Answer:
.NET Core uses ILogger<T> interface with built-in providers: Console, Debug, EventLog,
Azure, etc. Example:

private readonly ILogger<MyController> _logger;


public MyController(ILogger<MyController> logger) { _logger =
logger; }
_logger.LogInformation("Processing request...");

52. How do you implement structured logging?


Answer:
Use message templates with named placeholders:

_logger.LogInformation("User {UserId} logged in at {Time}", userId,


[Link]);

Structured logs can be processed by ELK/Seq for analytics.

53. What is Serilog and why is it used?


Answer:
Serilog is a third-party logging library for structured, configurable, and sink-based logging. It
supports JSON logs, files, databases, and logging pipelines for modern apps.

54. Difference between synchronous and asynchronous logging.


Answer:

● Synchronous: Logs immediately in the thread context; may affect performance.

● Asynchronous: Logs queued and processed separately, improving throughput and


reducing blocking.

55. How do you monitor performance in .NET Core Web API?


Answer:

● Use Application Insights or Prometheus/Grafana.

● Add custom logging for execution times.

● Monitor database query times with EF Core ToQueryString() or profiling tools.

Section 10: Caching and Performance


56. How do you implement caching in [Link] Core Web API?
Answer:
● In-memory caching: IMemoryCache for server-side caching.

● Distributed caching: IDistributedCache for multi-server scenarios (Redis, SQL


Server).

● Response caching: [ResponseCache(Duration=60)] caches HTTP responses.

57. Difference between in-memory and distributed caching.


Answer:

● In-memory: Single-server, fast, cleared on app restart.

● Distributed: Shared across servers, persistent, suitable for load-balanced apps.

58. What is Response Caching Middleware?


Answer:
It caches entire HTTP responses to reduce processing for repeated requests. Works with
headers like Cache-Control, Vary, and [ResponseCache].

59. How do you improve EF Core performance?


Answer:

● Use AsNoTracking for read-only queries.

● Avoid N+1 query problems with Include or ThenInclude.

● Use compiled queries for repetitive LINQ queries.

● Optimize database indexes and query projections.

60. What are compiled queries in EF Core?


Answer:
Compiled queries allow precompiling LINQ expressions to improve performance for
frequently executed queries.

Section 11: Advanced Web API Topics


61. How do you implement versioning with URL, query string, and header?
Answer:

● URL: /api/v1/products

● Query string: /api/products?api-version=1.0

● Header: api-version: 1.0


Use [Link] package and configure in
[Link].

62. How do you implement HATEOAS in Web API?


Answer:
HATEOAS (Hypermedia as the Engine of Application State) includes links in responses to
guide clients. Example:

{
"id": 1,
"name": "Product",
"links": [
{"rel": "self", "href": "/api/products/1"},
{"rel": "update", "href": "/api/products/1"}
]
}

63. How do you implement content negotiation in [Link] Core?


Answer:
Content negotiation automatically selects the appropriate format (JSON, XML) based on
Accept header. Configure in Startup:

[Link]().AddXmlSerializerFormatters();

64. Difference between synchronous and asynchronous controllers.


Answer:

● Synchronous: Blocking calls; can lead to thread starvation under load.

● Asynchronous: Uses async/await, non-blocking, better scalability for I/O-bound


operations.

65. How do you implement gRPC services in .NET Core?


Answer:

● Add [Link] package.

● Define .proto files.

● Implement service contracts and host via Kestrel.

● gRPC is fast and strongly typed for microservices communication.

Section 12: Asynchronous Programming and


Performance
66. How do you implement asynchronous actions in Web API?
Answer:
Use async/await with Task return types:

[HttpGet("{id}")]

public async Task<IActionResult> GetAsync(int id)

var item = await _context.[Link](id);

return Ok(item);

Asynchronous actions free up threads, improving scalability for I/O-bound operations.

67. Difference between Task and ValueTask.


Answer:

● Task: Represents an asynchronous operation, always allocates an object.

● ValueTask: Can avoid allocations for frequently completed operations; more


efficient but requires careful handling.

68. What is ConfigureAwait(false) and when to use it?


Answer:
ConfigureAwait(false) tells the compiler not to resume on the original synchronization
context. Useful in libraries or Web API where you don’t need to resume on the request
context, improving performance.

69. How do you prevent thread starvation in [Link] Core?


Answer:

● Avoid blocking calls ([Link](), .Result).

● Use async/await for I/O operations.

● Limit long-running CPU-bound tasks to background services (IHostedService or


queues).

70. What is the difference between I/O-bound and CPU-bound operations?


Answer:

● I/O-bound: Waiting on external resources (disk, network). Use async/await.

● CPU-bound: Heavy computations. Offload to background threads or services.


Section 13: Middleware Deep Dive
71. How do you implement global exception handling middleware?
Answer:

public class ExceptionMiddleware

private readonly RequestDelegate _next;

private readonly ILogger<ExceptionMiddleware> _logger;

public ExceptionMiddleware(RequestDelegate next,


ILogger<ExceptionMiddleware> logger)

_next = next;

_logger = logger;

public async Task InvokeAsync(HttpContext context)

try { await _next(context); }

catch (Exception ex)

_logger.LogError(ex, "Unhandled exception");

[Link] = 500;

await [Link]("Internal Server


Error");

}
72. Difference between short-circuiting and terminal middleware.
Answer:

● Short-circuiting: Stops the pipeline temporarily (e.g., authentication fails).

● Terminal middleware: Ends the request without passing to further middleware (e.g.,
[Link]()).

73. How do you share data between middleware components?


Answer:
Use [Link] dictionary to store and retrieve data between middleware in the
same request.

74. Difference between Use and MapWhen.


Answer:

● Use: Executes middleware in pipeline, optionally calls next.

● MapWhen: Branches pipeline based on a condition, runs only for matching requests.

75. How do you handle CORS dynamically in middleware?


Answer:
You can inspect [Link]["Origin"] and set Access-
Control-Allow-Origin dynamically for each request based on allowed origins.

Section 14: Testing


76. How do you unit test controllers in Web API?
Answer:

● Mock dependencies using frameworks like Moq.

● Call controller actions directly and assert results:

var result = await [Link](1);

[Link]<OkObjectResult>(result);

77. How do you test middleware?


Answer:

● Use TestServer from [Link].


● Simulate HTTP requests and inspect responses.

78. Difference between unit tests, integration tests, and functional tests.
Answer:

● Unit tests: Test individual components in isolation.

● Integration tests: Test multiple components working together, often with a real or in-
memory database.

● Functional tests: End-to-end tests simulating real user interactions.

79. How do you mock EF Core DbContext?


Answer:

● Use InMemoryDatabase provider for integration-like tests.

● Use mocking frameworks like Moq to mock DbSet<T> for unit tests.

80. How do you test async actions?


Answer:
Use async Task test methods and await the controller or service calls:

[Fact]

public async Task GetItem_ReturnsOk()

var result = await [Link](1);

[Link]<OkObjectResult>(result);

Section 15: Advanced EF Core


81. How do you handle concurrency in EF Core?
Answer:

● Use optimistic concurrency with [Timestamp] or RowVersion column.

● Catch DbUpdateConcurrencyException and handle conflicts by retrying or


informing the user.
82. Difference between eager, lazy, and explicit loading.
Answer:

● Eager loading: Include() loads related entities immediately.

● Lazy loading: Loads related entities on-demand (requires proxies).

● Explicit loading: Load related entities manually via


[Link](entity).Collection(...).

83. How do you optimize large queries in EF Core?


Answer:

● Use projections (Select) to fetch only required columns.

● Use AsNoTracking() for read-only queries.

● Split queries instead of single complex joins.

84. What is shadow property in EF Core?


Answer:
A shadow property exists in the model but not in the C# class. It can store additional data
like foreign keys, without modifying entity classes.

85. How do you handle migrations in production safely?


Answer:

● Test migrations on staging.

● Use transactional migrations if supported.

● Backup database before migration.

● Apply migrations incrementally or manually in CI/CD pipelines.

Section 16: Microservices and SignalR


86. How do you design Web API for microservices?
Answer:

● Small, focused services with clear boundaries.

● Use REST or gRPC for communication.

● Decentralized data storage.


● Implement API gateway, service discovery, and message-based communication
(e.g., RabbitMQ, Kafka).

87. What is SignalR and when to use it?


Answer:
SignalR is a library for real-time communication in .NET Core. Use it for chat apps, live
dashboards, notifications, or multiplayer games.

88. How do you implement SignalR Hub?


Answer:

● Define a Hub class inheriting from Hub.

● Configure endpoints in [Link]:


[Link]<ChatHub>("/chathub");

● Clients connect via JavaScript or .NET client.

89. Difference between WebSockets and Server-Sent Events (SSE).


Answer:

● WebSockets: Full-duplex, bi-directional communication.

● SSE: Server-to-client only, one-way push.

90. How do you handle scaling SignalR in multi-server environment?


Answer:
Use a backplane like Redis or Azure SignalR Service to coordinate messages between
servers.

Section 17: Logging and Diagnostics Advanced


91. How do you implement structured logging with Serilog?
Answer:

[Link] = new LoggerConfiguration()

.[Link]()

.[Link]()

.[Link]("logs/[Link]", rollingInterval:
[Link])

.CreateLogger();
Use placeholders for structured data:

[Link]("User {UserId} created an order {OrderId}", userId,


orderId);

92. How do you integrate Application Insights in Web API?


Answer:

● Add [Link] package.

● Configure instrumentation key in [Link].

● Use TelemetryClient to track requests, exceptions, dependencies.

93. What is correlation ID and why is it used?


Answer:
Correlation ID is a unique identifier for a request to trace logs across services. Useful for
distributed microservices debugging.

94. How do you implement health checks in .NET Core?


Answer:

[Link]()

.AddSqlServer([Link]("DefaultConnecti
on"));

[Link](endpoints => [Link]("/health"));

Used by orchestration platforms like Kubernetes to monitor service health.

95. Difference between ILogger and Trace in .NET Core.


Answer:

● ILogger: Modern, flexible, structured logging with dependency injection.

● Trace: Legacy diagnostic logging, less flexible, mainly for debugging.

Section 18: Error Handling and Exception Management


96. How do you return problem details in Web API?
Answer:
Use ProblemDetails for standard RFC7807 error responses:
return Problem(detail: "Invalid operation", statusCode: 400, title:
"Bad Request");

97. How do you differentiate between client and server errors?


Answer:

● Client errors (4xx): Invalid input, unauthorized, not found.

● Server errors (5xx): Exceptions, failed dependencies, unhandled errors.

98. How do you log exceptions globally?


Answer:

● Create custom middleware to catch exceptions and log using ILogger.

● Use UseExceptionHandler() in [Link] for centralized handling.

99. Difference between try-catch in action method vs middleware.


Answer:

● Middleware: Centralized, reusable, global handling.

● Action-level: Specific to controller or action, less reusable.

100. How do you implement retry logic for transient failures?


Answer:
Use libraries like Polly:

var retryPolicy = [Link]<HttpRequestException>()

.WaitAndRetryAsync(3, retryAttempt =>


[Link](retryAttempt));

await [Link](() => [Link](url));

Section 19: Advanced Asynchronous Programming


101. How do you cancel asynchronous operations in .NET Core?
Answer:
Use CancellationToken:

public async Task<IActionResult> GetAsync(CancellationToken


cancellationToken)

{
var data = await _context.[Link](cancellationToken);

return Ok(data);

Pass the token down to async methods to support cooperative cancellation.

102. How do you handle exceptions in async methods?


Answer:
Use try-catch with await. Unhandled exceptions in Task bubble up to the calling method:

try { await DoAsync(); }

catch(Exception ex) { _logger.LogError(ex, "Error"); }

103. Difference between [Link] and [Link].


Answer:

● [Link]: Simple, schedules work on thread pool, recommended for CPU-bound


operations.

● [Link]: More configurable, can specify task options, rarely


needed in modern code.

104. How do you avoid deadlocks with async/await?


Answer:

● Avoid .Result or .Wait() on async code.

● Use ConfigureAwait(false) in library code to prevent context capture.

105. What is IAsyncEnumerable in C#?


Answer:
IAsyncEnumerable<T> allows streaming of asynchronous data using await foreach.
Useful for large datasets to reduce memory usage.

Section 20: Advanced EF Core Topics


106. How do you implement soft delete in EF Core?
Answer:
Add a IsDeleted property and override SaveChanges or use global query filters:

[Link]<Item>().HasQueryFilter(p => ![Link]);


107. How do you implement auditing (created/updated timestamps) in EF Core?
Answer:
Override SaveChanges or use ChangeTracker to set timestamps before saving.

108. What are shadow properties in EF Core?


Answer:
Properties in EF Core that exist in the model but not in the C# class, useful for storing
foreign keys without modifying entities.

109. How do you handle many-to-many relationships?


Answer:
Use EF Core 5+ native many-to-many support or define a join entity explicitly for complex
scenarios.

110. How do you optimize EF Core for high-volume queries?


Answer:

● Use AsNoTracking for read-only queries.

● Select only necessary columns.

● Use compiled queries for frequently executed LINQ expressions.

Section 21: Caching Strategies


111. Difference between memory cache and distributed cache.
Answer:

● Memory cache: Single server, fast, non-persistent.

● Distributed cache: Multi-server, persistent (Redis, SQL Server).

112. How do you implement Redis caching in .NET Core?


Answer:

[Link](options => {

[Link] = "localhost:6379";

});

Use IDistributedCache to store/retrieve serialized data.

113. What is response caching and how does it work?


Answer:
Caches HTTP responses based on headers (Cache-Control) to reduce server load. Use
[ResponseCache] or middleware.

114. How do you cache complex objects?


Answer:
Serialize objects to JSON or binary format before caching. Deserialize when reading back.

115. How do you implement cache expiration and invalidation?


Answer:

● Use absolute expiration (AbsoluteExpirationRelativeToNow) or sliding


expiration (SlidingExpiration).

● Manually remove cache when data changes to avoid stale data.

Section 22: Web API Versioning & HATEOAS


116. How do you implement API versioning using URL segment?
Answer:

[ApiVersion("1.0")]

[Route("api/v{version:apiVersion}/[controller]")]

Versioning is then derived from the URL.

117. How do you implement query string versioning?


Answer:
Configure API versioning in Startup and access via ?api-version=1.0.

118. What is HATEOAS and how is it implemented?


Answer:
HATEOAS adds links to API responses so clients can navigate the API dynamically. Include
links in JSON responses.

119. Difference between versioning in headers vs URL.


Answer:

● Header: Cleaner URLs, version hidden from users, better for RESTful standards.

● URL: Easy to test manually, clearly visible, but URL changes with version.

120. How do you deprecate old API versions?


Answer:

● Mark version as deprecated in API versioning config.


● Return warning headers or responses informing clients.

● Remove from documentation gradually.

Section 23: gRPC & SignalR Advanced


121. Difference between REST and gRPC.
Answer:

● REST: Text-based (JSON), loosely coupled, widely supported.

● gRPC: Binary protocol (Protobuf), strongly typed, high-performance, ideal for


microservices.

122. How do you implement gRPC streaming?


Answer:

● Server streaming: Server sends multiple responses to a single client request.

● Client streaming: Client sends multiple messages to server.

● Bidirectional streaming: Both client and server send streams concurrently.

123. How do you scale SignalR in a multi-server setup?


Answer:
Use Redis backplane or Azure SignalR Service to coordinate messages across servers.

124. What transport protocols does SignalR use?


Answer:
SignalR chooses automatically between WebSockets, Server-Sent Events (SSE), and Long
Polling depending on client and server capabilities.

125. How do you handle client disconnections in SignalR?


Answer:
Override OnDisconnectedAsync in Hub to clean up resources or update connection
state.

Section 24: Security Deep Dive


126. How do you implement OAuth2 in .NET Core Web API?
Answer:

● Use IdentityServer4 or Azure AD.

● Configure clients, scopes, and endpoints.


● Validate tokens with [Authorize] and policies.

127. Difference between OAuth2 and OpenID Connect.


Answer:

● OAuth2: Authorization framework, controls access to resources.

● OpenID Connect: Identity layer on top of OAuth2, provides authentication.

128. How do you implement refresh tokens?


Answer:

● Generate long-lived refresh tokens alongside short-lived access tokens.

● Store refresh tokens securely and validate when issuing new access tokens.

129. How do you prevent replay attacks in JWT?


Answer:

● Use short-lived access tokens.

● Use jti (JWT ID) claims and track used tokens.

● Enforce HTTPS.

130. How do you implement rate limiting in Web API?


Answer:
Use middleware or libraries (e.g., AspNetCoreRateLimit) to limit requests per client/IP,
return 429 Too Many Requests.

Section 25: Logging, Monitoring & Diagnostics


131. How do you implement correlation IDs?
Answer:

● Generate a unique ID per request.

● Include in logs using ILogger context.

● Pass to downstream services for tracing.

132. How do you integrate structured logging with Serilog?


Answer:

● Configure sinks for console, file, or external systems.


● Use placeholders for structured data.

● Example:

[Link]("Order {OrderId} processed by user {UserId}",


orderId, userId);

133. How do you monitor performance with Application Insights?


Answer:

● Track requests, dependencies, exceptions, and custom metrics.

● Use TelemetryClient to log custom events.

● Visualize dashboards and alerts in Azure.

134. How do you implement health checks in Kubernetes?


Answer:

● Use AddHealthChecks and map endpoint /health.

● Configure liveness and readiness probes in deployment YAML.

135. How do you diagnose memory leaks in Web API?


Answer:

● Use dotnet-counters, PerfView, or Visual Studio Memory Profiler.

● Look for un-disposed objects, static references, or cached collections.

Section 26: Advanced Caching and Performance


136. How do you implement sliding expiration in caching?
Answer:
Sliding expiration resets the cache timer each time the item is accessed:

[Link]("key", value, new MemoryCacheEntryOptions


{ SlidingExpiration = [Link](10) });

137. How do you implement cache invalidation?


Answer:
● Manually remove cache: [Link]("key")

● Use cache dependencies (Redis pub/sub)

● Set absolute expiration

138. How do you handle distributed cache consistency?


Answer:

● Use Redis or other distributed stores.

● Apply proper expiration policies.

● Use cache-aside pattern to ensure consistency with the database.

139. Difference between cache-aside, write-through, and write-behind strategies.


Answer:

● Cache-aside: Application reads/writes directly to DB; cache updated on demand.

● Write-through: Writes go through cache to DB.

● Write-behind: Writes go to cache, asynchronously persisted to DB.

140. How do you optimize Web API performance?


Answer:

● Use async/await

● Cache frequently used data

● Optimize EF Core queries

● Enable response compression

● Use connection pooling and indexing

Section 27: Microservices & Messaging


141. How do you implement event-driven architecture?
Answer:

● Use messaging systems like RabbitMQ, Kafka, or Azure Service Bus

● Services publish/subscribe to events

● Promotes loose coupling and scalability


142. Difference between synchronous and asynchronous communication in
microservices.
Answer:

● Synchronous: Direct request/response, blocking

● Asynchronous: Event-driven, decoupled, non-blocking

143. How do you implement message queuing with RabbitMQ in .NET Core?
Answer:

● Use [Link] package

● Declare exchanges, queues, bindings

● Publish messages and consume using background services

144. How do you implement saga pattern for distributed transactions?


Answer:

● Break transaction into smaller steps

● Compensate steps on failure

● Coordinate using events or orchestration service

145. How do you implement API Gateway?


Answer:

● Acts as entry point for microservices

● Handles routing, authentication, rate limiting, and aggregation

● Examples: Ocelot in .NET Core

Section 28: Testing & CI/CD


146. How do you write integration tests for Web API?
Answer:

● Use WebApplicationFactory or TestServer

● Mock external dependencies or use in-memory DB

● Send HTTP requests and assert responses


147. Difference between mocking and faking in tests.
Answer:

● Mock: Simulate behavior with assertions

● Fake: Lightweight implementation for testing

148. How do you implement continuous integration for .NET Core projects?
Answer:

● Use Azure DevOps, GitHub Actions, or Jenkins

● Build, run tests, and create artifacts automatically on code commit

149. How do you implement continuous deployment?


Answer:

● Deploy artifacts to staging/production automatically

● Can include infrastructure as code

● Rollback strategies for failed deployments

150. How do you run tests in CI pipeline?


Answer:

● Use dotnet test in pipeline YAML

● Publish test results to CI server

● Integrate code coverage tools

Section 29: Deployment & Containers


151. How do you containerize .NET Core Web API with Docker?
Answer:

● Use Dockerfile:

FROM [Link]/dotnet/aspnet:7.0 AS base

WORKDIR /app

EXPOSE 80

FROM [Link]/dotnet/sdk:7.0 AS build


WORKDIR /src

COPY . .

RUN dotnet publish -c Release -o /app

FROM base AS final

WORKDIR /app

COPY --from=build /app .

ENTRYPOINT ["dotnet", "[Link]"]

● Build image and run container

152. How do you deploy Web API to Azure App Service?


Answer:

● Publish via Visual Studio, CLI, or CI/CD pipeline

● Configure environment variables in App Settings

● Enable Application Insights for monitoring

153. How do you deploy using Kubernetes?


Answer:

● Create Deployment, Service, and ConfigMap YAML files

● Use kubectl apply -f to deploy

● Use liveness and readiness probes

154. How do you implement zero-downtime deployment?


Answer:

● Use rolling updates in Kubernetes or App Service deployment slots

● Monitor health checks before switching traffic

155. How do you handle environment-specific configurations?


Answer:

● Use appsettings.{Environment}.json

● Use environment variables


● Use IOptions<T> for strongly typed configs

Section 30: Logging, Monitoring & Observability


156. How do you centralize logs for microservices?
Answer:

● Use ELK stack (Elasticsearch, Logstash, Kibana) or Seq

● Push logs from all services using structured logging

157. How do you trace requests across microservices?


Answer:

● Use correlation IDs

● Distributed tracing with OpenTelemetry, Jaeger, or Application Insights

158. How do you monitor performance metrics?


Answer:

● Track requests, response times, CPU/memory usage

● Use Prometheus/Grafana or Application Insights

159. How do you implement alerts for failures?


Answer:

● Configure metrics thresholds in monitoring system

● Send notifications via email, Slack, or PagerDuty

160. How do you implement health checks in microservices?


Answer:

● Use AddHealthChecks in each service

● Include database, cache, and dependency checks

Section 31: Error Handling & Best Practices


161. How do you handle global exceptions in microservices?
Answer:
● Use centralized exception middleware

● Log exception details

● Return structured error responses

162. How do you implement validation globally?


Answer:

● Use FluentValidation

● Use [ApiController] attribute for automatic model validation

163. How do you implement consistent API responses?


Answer:

● Create a standard response wrapper with status, message, and data

● Include error codes for clients

164. How do you implement graceful shutdown in .NET Core?


Answer:

● Implement IHostedService

● Handle ApplicationStopping token

● Complete background tasks before shutting down

165. How do you avoid memory leaks?


Answer:

● Dispose IDisposable objects

● Avoid capturing long-lived objects in closures

● Monitor with memory profilers

Section 32: Advanced Security & Authentication


166. How do you implement multi-factor authentication?
Answer:

● Use Identity or third-party providers


● Require password + OTP/email code

● Integrate with JWT or cookie auth

167. How do you implement role-based authorization?


Answer:

[Authorize(Roles = "Admin")]

● Assign roles in Identity or custom DB

● Policies can combine roles and claims

168. How do you implement policy-based authorization?


Answer:

[Link](options =>

[Link]("AdminOnly", policy =>

[Link]("Admin")));

● Apply [Authorize(Policy = "AdminOnly")]

169. How do you secure secrets in Web API?


Answer:

● Use environment variables or Key Vault

● Avoid hardcoding secrets

● Rotate secrets regularly

170. How do you protect against brute-force attacks?


Answer:

● Implement account lockout after failed attempts

● Use CAPTCHA for login endpoints

● Rate-limit login requests

Section 33: CI/CD and DevOps


171. How do you implement CI/CD for .NET Core Web API?
Answer:

● Use pipelines in GitHub Actions, Azure DevOps, or Jenkins.

● Steps: build → run tests → create artifact → deploy to staging/production.

● Automate database migrations and environment configuration.

172. How do you automate database migrations in CI/CD?


Answer:

● Use EF Core CLI commands: dotnet ef migrations add and dotnet ef


database update.

● Apply migrations in pipeline before deployment.

173. How do you implement rollback in deployments?


Answer:

● Use deployment slots in Azure App Service.

● In Kubernetes, keep previous pods and use rolling update with maxUnavailable
and maxSurge.

● Maintain versioned artifacts to revert easily.

174. How do you handle secrets in CI/CD pipelines?


Answer:

● Store secrets in environment variables, Key Vault, or pipeline secret storage.

● Avoid committing secrets to source control.

175. How do you implement blue/green deployment?


Answer:

● Deploy new version to a separate environment (green).

● Switch traffic from old version (blue) to new version when ready.

● Ensures zero downtime and rollback ability.

Section 34: Advanced Microservices Patterns


176. What is the Circuit Breaker pattern?
Answer:
● Prevents cascading failures in microservices by halting requests to a failing service.

● Can be implemented using Polly library in .NET Core.

177. What is the Bulkhead pattern?


Answer:

● Isolates resources or services to prevent failures in one area from affecting others.

178. What is the Retry pattern?


Answer:

● Automatically retry failed requests based on rules (fixed delay, exponential backoff).

179. How do you implement distributed locking?


Answer:

● Use Redis or SQL-based locks to prevent race conditions in multi-instance


environments.

180. How do you implement sagas for long-running transactions?


Answer:

● Break transaction into steps across services.

● Compensate failed steps with reverse actions.

● Use orchestration or choreography approaches.

Section 35: Advanced Messaging


181. How do you implement message queuing with Azure Service Bus?
Answer:

● Create namespace and queue.

● Publish messages using [Link].

● Consume messages with MessageHandlerOptions and


RegisterMessageHandler.

182. How do you implement publish/subscribe messaging?


Answer:

● Services publish events to a topic.


● Subscribers listen to specific events and act accordingly.

183. How do you handle message duplication?


Answer:

● Use idempotent consumers.

● Deduplicate using unique message IDs or persistence.

184. How do you implement delayed messages?


Answer:

● Use message scheduling features in RabbitMQ or Azure Service Bus.

● Set ScheduledEnqueueTime or delay queues.

185. How do you handle dead-letter messages?


Answer:

● Use dead-letter queues (DLQ) to capture failed messages.

● Analyze and retry or discard them.

Section 36: Advanced Deployment & Containerization


186. How do you optimize Docker images for Web API?
Answer:

● Use multi-stage builds to reduce final image size.

● Remove unnecessary files and dependencies.

● Use runtime-only images (aspnet vs sdk) for production.

187. How do you handle environment-specific settings in Docker?


Answer:

● Use environment variables or Docker secrets.

● Mount configuration files as volumes.

188. How do you scale Web API in Kubernetes?


Answer:

● Configure Deployment replicas.


● Use Horizontal Pod Autoscaler (HPA) for load-based scaling.

● Load balancing via Services or Ingress.

189. How do you implement rolling updates in Kubernetes?


Answer:

● Update Deployment image with new version.

● Configure maxUnavailable and maxSurge to control rollout speed.

190. How do you implement canary deployments?


Answer:

● Deploy new version to small subset of users/pods.

● Monitor metrics and gradually increase traffic.

Section 37: Advanced Performance Tuning


191. How do you profile Web API performance?
Answer:

● Use dotnet-counters, dotnet-trace, or Application Insights.

● Measure request times, DB queries, memory usage.

192. How do you optimize database calls?


Answer:

● Use projections (Select) to fetch only needed columns.

● Apply indexes on frequently queried columns.

● Use caching for repeated queries.

193. How do you reduce payload size in Web API responses?


Answer:

● Use DTOs to send only necessary fields.

● Compress responses with Gzip or Brotli middleware.

194. How do you reduce cold start in cloud deployment?


Answer:
● Use pre-warmed instances (App Service), or container warm-up probes.

195. How do you implement connection pooling?


Answer:

● Use built-in [Link] connection pooling (default in EF Core).

● Set Max Pool Size and Min Pool Size appropriately.

Section 38: Observability & Troubleshooting


196. How do you implement distributed tracing?
Answer:

● Use OpenTelemetry or Application Insights.

● Propagate trace IDs across services via headers.

197. How do you analyze slow requests?


Answer:

● Use Application Insights or logging middleware.

● Track request duration and database query times.

198. How do you troubleshoot memory leaks?


Answer:

● Use memory profilers, GC logs, and heap snapshots.

● Identify un-disposed objects or static references.

199. How do you implement request logging and metrics?


Answer:

● Middleware to log request/response details.

● Increment counters for metrics (Prometheus counters or Application Insights).

200. Best practices for building high-performance, secure Web APIs in .NET Core?
Answer:

● Use async/await for I/O-bound tasks

● Apply caching and compression


● Implement proper authentication & authorization

● Monitor logs, metrics, and distributed tracing

● Optimize database queries and connection pooling

● Use versioning, consistent responses, and proper error handling

● Containerize for portability and scale using Kubernetes or cloud services

Common questions

Powered by AI

Prevent memory leaks by avoiding un-disposed objects and static references, and using caching cautiously . Regular memory leak monitoring in .NET can be accomplished using tools like dotnet-counters, PerfView, or Visual Studio Memory Profiler to track object retention across garbage collections and un-disposed resources . Use logging of memory metrics and configure garbage collection settings appropriately to minimize leaks .

CDNs offer benefits like reduced latency, decreased load on API servers, and improved performance by caching assets closer to users globally . Challenges include managing cache invalidation, ensuring SSL handshake consistency, and potential complexity in DNS management . Despite challenges, CDNs effectively enhance scalability and global performance, especially for asset distribution .

To manage thread safety within singleton services in .NET Core, avoid shared mutable static state and race conditions. Use locking mechanisms or concurrency-safe collections when mutable shared state is inevitable. Design with immutability in mind whenever possible to naturally circumvent concurrency issues . Ensure the internal state is properly synchronized and thread-safe .

API versioning in ASP.NET Core can be implemented using URL segments, where the version is part of the URL path (e.g., "api/v1/[controller]"). This approach makes the version explicit and clear for consumers, easing routing and operation. Although it constrains the URL scheme, it provides a straightforward way to manage and test different API versions simultaneously .

Cross-cutting concerns such as logging, validation, caching, and authorization in a .NET Web API can be handled using middleware, filters, attributes, and policies. Dependency Injection (DI) is utilized to inject behaviors, while interceptors or aspects (AOP) can also be employed where necessary .

Health checks in ASP.NET Core are implemented using the AddHealthChecks method. The /health endpoint is then mapped to expose these checks. Within Kubernetes, liveness and readiness probes are configured based on these health endpoints to automatically detect application failures and trigger appropriate responses, like restarting or rerouting requests, thereby ensuring system reliability and minimizing downtime .

gRPC uses HTTP/2 for transport and is ideal for scenarios requiring low latency and high throughput, offering features like bi-directional streaming and precise service contracts . In contrast, REST is stateless, works over HTTP 1.1, and is easy to implement with wide support across web environments, making it suitable when resource-oriented APIs and broader accessibility are needed. Choose gRPC for highly performant internal microservices, and REST for public APIs needing wide accessibility and compatibility with web browsers .

OpenTelemetry in .NET Core can be configured by installing appropriate OpenTelemetry packages and setting it up in Program.cs. You can add instrumentation for various facets like ASP.NET Core applications, HTTP client requests, and EF Core operations. The data can then be exported to monitoring backends such as Jaeger or Zipkin for analysis .

Consistent API responses are achieved by implementing a standard response wrapper that includes status, message, and data fields. This uniformity helps clients reliably parse responses and make error handling predictable. Consistency is critical for usability, reduces complexity in client-side error handling, and ensures a smooth developer experience .

Socket exhaustion occurs when HttpClient instances are not disposed and their connections remain open, leading to issues like resource starvation . Using the IHttpClientFactory allows better management of HttpClient lifetimes and connections, thus preventing socket exhaustion by promoting the reuse of handlers and enabling the usage of named clients for configuration, thereby managing resources effectively .

You might also like