Skip to main content

Salesforce Interview ASP.NET Web API Interview Questions

Curated Salesforce Interview-level ASP.NET Web API interview questions for developers targeting salesforce interview positions. 113 questions available.

Last updated:

ASP.NET Web API Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of ASP.NET Web API interview questions and answers. This page contains expertly curated interview questions covering all aspects of ASP.NET Web API, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our ASP.NET Web API interview questions are designed to help you:

  • Understand core concepts and best practices in ASP.NET Web API
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next ASP.NET Web API interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic ASP.NET Web API concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

113 questions
Q1:

What is ASP.NET Core Web API and how does it differ from MVC?

Entry

Answer

ASP.NET Core Web API is a framework for building HTTP services that return JSON, XML, or other serialized data.

Differences from MVC:

  • No Razor or HTML rendering
  • Focused on RESTful services
  • Controller methods return data, not views
  • Routing is often attribute-based
Q2:

Explain the request pipeline in ASP.NET Core Web API.

Entry

Answer

The pipeline consists of middleware components that process HTTP requests in sequence:

  • Request enters server
  • Middleware handles tasks like authentication, logging, routing
  • Endpoint routing selects controller/action
  • Controller executes business logic
  • Response flows back through middleware
Q3:

What are Controllers and how are they structured?

Entry

Answer

Controllers handle incoming HTTP requests.

  • Decorated with [ApiController] and [Route]
  • Contain action methods
  • Use dependency injection via constructor
  • Return IActionResult or data objects
Q4:

How does Attribute Routing work in Web API?

Entry

Answer

Attribute routing uses attributes to define URL patterns.

  • [Route("api/[controller]")] sets base route
  • [HttpGet], [HttpPost] define HTTP verbs
  • Supports route parameters, constraints, defaults
Q5:

Explain model binding and validation.

Entry

Answer

Model binding maps HTTP data to method parameters.

  • [FromBody] binds JSON/XML
  • [FromQuery] binds query parameters
  • [FromRoute] binds URL segments

Validation uses DataAnnotations and ModelState.IsValid.

Q6:

What are Action Results and why are they important?

Entry

Answer

Action results allow APIs to return proper HTTP responses.

  • Return 200, 404, 400 etc.
  • Provide flexibility using IActionResult
  • Support multiple return formats
Q7:

What is Content Negotiation in Web API?

Entry

Answer

Content negotiation selects the response format based on:

  • Client's Accept header
  • Configured formatters (JSON, XML)

ASP.NET Core defaults to JSON.

Q8:

How are dependency injection and services handled in Web API?

Entry

Answer

ASP.NET Core has built-in DI.

  • Register services using AddSingleton/AddScoped/AddTransient
  • Injected via controller constructor
  • Improves modularity and testability
Q9:

Explain the difference between Scoped, Singleton, and Transient lifetimes.

Entry

Answer

Singleton: One instance for entire app.

Scoped: One instance per request.

Transient: New instance per usage.

Q10:

How do you handle exceptions in Web API?

Entry

Answer

Best practices include:

  • UseExceptionHandler middleware
  • Exception filters
  • Centralized logging
  • Returning friendly error messages
Q11:

How does ASP.NET Core handle JSON serialization?

Entry

Answer

Uses System.Text.Json by default.

  • High performance
  • Supports converters and casing rules
  • Can switch to Newtonsoft.Json if required
Q12:

What are Action Filters and when do you use them?

Entry

Answer

Action filters run before/after actions.

  • Logging
  • Validation
  • Authentication
  • Response modification
Q13:

Explain the purpose of FromBody, FromQuery, and FromRoute.

Entry

Answer

[FromBody] - reads body JSON/XML.

[FromQuery] - reads query string.

[FromRoute] - maps URL parameters.

Q14:

How do you implement versioning in Web API?

Entry

Answer

API versioning methods:

  • URL versioning: /api/v1/
  • Query string versioning
  • Header versioning (api-version)

Implemented using the Versioning package.

Q15:

What is CORS and why is it important in Web API?

Entry

Answer

CORS allows cross-domain API access.

Configured using AddCors + middleware.

Needed for browser-based clients.

Q16:

How do you secure a Web API?

Entry

Answer

Security techniques include:

  • JWT Bearer authentication
  • [Authorize] attributes
  • HTTPS enforcement
  • Input validation
  • Rate limiting
Q17:

Explain the difference between synchronous and asynchronous controllers.

Entry

Answer

Synchronous: Thread waits for completion.

Asynchronous: Releases thread during I/O.

Async improves scalability.

Q18:

What is Response Caching in Web API?

Entry

Answer

Response caching reduces repeated processing.

  • Uses [ResponseCache] attribute
  • Decreases latency
  • Improves throughput
Q19:

How do you test a Web API effectively?

Entry

Answer

Testing involves:

  • Unit tests with mocks
  • Integration tests with TestServer
  • API testing tools (Postman, Swagger)
  • Validating status codes, payloads, headers
Q20:

Why is Swagger/OpenAPI important in Web API?

Entry

Answer

Swagger provides:

  • Interactive API documentation
  • Endpoint visibility
  • Contract testing
  • Client-code generation
Q21:

What is Middleware in ASP.NET Core Web API?

Entry

Answer

Middleware are components in the ASP.NET Core request pipeline that execute sequentially.

Each middleware can:

  • Process the request before passing it forward
  • Process the response after the next middleware has executed

Common examples include authentication, logging, CORS, and routing middleware.

Order is critical because each middleware depends on the sequence.

Q22:

How does the UseRouting and UseEndpoints middleware work?

Entry

Answer

UseRouting identifies the matching endpoint based on the URL.

UseEndpoints executes the matched action.

Authentication, authorization, and CORS middleware should be placed between these two for correct behavior.

Q23:

How do you create custom middleware?

Entry

Answer

Custom middleware involves:

  • Create a class with a constructor accepting RequestDelegate
  • Implement Invoke or InvokeAsync
  • Register with app.UseMiddleware<T>()
Q24:

Explain Filters in ASP.NET Core Web API.

Entry

Answer

Filters run during the execution pipeline and include:

  • Authorization Filters
  • Resource Filters
  • Action Filters
  • Exception Filters
  • Result Filters
Q25:

How is model validation applied automatically?

Entry

Answer

Applying [ApiController] automatically triggers model validation.

Invalid models result in 400 Bad Request with error details.

Validation uses DataAnnotations like [Required], [Range], etc.

Q26:

How do you implement global exception handling using middleware?

Entry

Answer

Global exception handling steps:

  • Create custom exception middleware
  • Wrap request processing in try/catch
  • Log and return a standardized error response
  • Use app.UseExceptionHandler() for production mode
Q27:

Explain the difference between synchronous and asynchronous middleware.

Entry

Answer

Synchronous middleware: Blocks thread while executing.

Asynchronous middleware: Uses Task and await to release thread during I/O operations.

Async middleware improves scalability in high-load systems.

Q28:

How can you implement logging in Web API?

Entry

Answer

Logging methods:

  • Use ILogger<T> via DI
  • Log levels: Trace ? Critical
  • Send logs to Console, Files, DB, or external providers
  • Use middleware/filters for request & response logging
Q29:

What is diagnostic middleware and why is it important?

Entry

Answer

Diagnostic middleware provides insights into requests and system behavior.

Examples: DeveloperExceptionPage, SerilogRequestLogging, Application Insights.

Helps detect failures, anomalies, and performance issues.

Q30:

How do you handle CORS in a Web API?

Entry

Answer

CORS is configured using:

  • AddCors() in Program.cs
  • Define policies with allowed origins, headers, and methods
  • Apply globally or per controller using [EnableCors]
Q31:

How do you restrict content types in requests?

Entry

Answer

Use the [Consumes] attribute:

[Consumes("application/json")]

Rejects unsupported media types with HTTP 415.

Q32:

How do you inspect and log request/response bodies safely?

Entry

Answer

To log safely:

  • Use EnableBuffering() for reading request body
  • Wrap the response stream to capture outgoing body
  • Avoid logging sensitive data
Q33:

What is the difference between endpoint routing and legacy MVC routing?

Entry

Answer

Endpoint routing: Pre-matches endpoints before controller activation.

Legacy routing: Occurred during MVC action selection.

Endpoint routing is more flexible and enables better middleware integration.

Q34:

How do you implement API versioning?

Entry

Answer

Use API Versioning package.

  • URL versioning
  • Header versioning
  • Query string versioning

Decorate controllers with [ApiVersion("1.0")].

Q35:

How do you configure JSON serialization globally?

Entry

Answer

Configure using:

AddControllers().AddJsonOptions(options => { ... });

Supports camelCase, converters, and null handling.

Q36:

How do you handle API response formatting?

Entry

Answer

Use IActionResult or ActionResult<T> for flexible responses.

Supports content negotiation and custom response formatting.

Q37:

How do you throttle requests in ASP.NET Core Web API?

Entry

Answer

Use libraries like AspNetCoreRateLimit.

  • Define IP or user-based rate limits
  • Prevent abuse and DoS attacks
  • Supports rule-based throttling
Q38:

What are dependency injection best practices in Web API?

Entry

Answer

Best practices:

  • Use correct lifetimes: Singleton, Scoped, Transient
  • Prefer constructor injection
  • Avoid service locator pattern
  • Group and organize service registrations
Q39:

How do you monitor Web API performance in production?

Entry

Answer

Use monitoring platforms like:

  • Application Insights
  • Serilog + Seq
  • ELK Stack
  • Prometheus + Grafana

Track latency, errors, throughput, and resource usage.

Q40:

How do you implement authentication in Web API?

Junior

Answer

Authentication verifies user identity in Web API.

Common implementations:

  • JWT Bearer Tokens – stateless authentication for SPA and mobile apps.
  • OAuth2 / OpenID Connect – external identity providers.
  • Cookie authentication – mainly for browser-based apps.

Configured using AddAuthentication() and UseAuthentication().

Q41:

How does JWT authentication work?

Junior

Answer

JWT workflow:

  • User logs in ? server generates a signed JWT.
  • Client sends token in Authorization: Bearer <token>.
  • Server validates signature and extracts claims.
  • No server-side session required.
Q42:

How do you implement role-based authorization?

Junior

Answer

Use role-based authorization with:

[Authorize(Roles="Admin,Manager")]

Roles are validated from claims inside the JWT or identity provider.

Q43:

What is claims-based authorization?

Junior

Answer

Claims-based authorization checks user claims instead of static roles.

Implemented using policy-based authorization:

services.AddAuthorization(options =>
{
    options.AddPolicy("HRPolicy",
        policy => policy.RequireClaim("Department", "HR"));
});
Q44:

How do you create custom authorization policies?

Junior

Answer

Create policies in Program.cs using AddAuthorization.

Apply using [Authorize(Policy="PolicyName")].

Useful for domain-specific access control.

Q45:

What is the difference between authentication and authorization?

Junior

Answer

Authentication: Verifies user identity.

Authorization: Determines what the authenticated user can access.

Q46:

How do you secure sensitive API endpoints?

Junior

Answer

Secure endpoints using:

  • [Authorize] attribute
  • HTTPS enforcement
  • Input validation
  • Rate limiting
  • CORS restrictions
Q47:

How do you handle token expiration in JWT?

Junior

Answer

JWT includes an exp claim for expiration.

API rejects expired tokens automatically.

Refresh tokens extend the session securely.

Q48:

How do you protect against CSRF attacks in APIs?

Junior

Answer

API best practices:

  • Use JWT instead of cookies
  • Enable strict CORS policies
  • Use anti-forgery tokens if cookies are used
Q49:

How do you secure API keys in Web API?

Junior

Answer

Best practices:

  • Store in Key Vault or environment variables
  • Never hard-code keys
  • Rotate keys periodically
Q50:

What is OAuth2 and how is it used with Web API?

Junior

Answer

OAuth2 is a secure authorization framework.

Flow: Client ? Auth Server ? Access Token ? API.

Supports scopes, roles, and claims.

Q51:

How do scopes differ from roles in OAuth2?

Junior

Answer

Roles: Broad user categories.

Scopes: Fine-grained permissions such as read:orders.

Q52:

How do you implement token revocation?

Junior

Answer

Token revocation strategies:

  • Blacklist tokens in database
  • Short-lived access tokens
  • Rotating refresh tokens
Q53:

How do you implement multi-tenant security?

Junior

Answer

Multi-tenant API security includes:

  • Tenant ID in claims or headers
  • Middleware-based access validation
  • Database filtering by tenant context
Q54:

How do you prevent over-posting attacks?

Junior

Answer

Use DTOs instead of binding directly to entity models.

Expose only allowed fields.

Always validate incoming payloads.

Q55:

What are best practices for securing Web API endpoints?

Junior

Answer

  • Force HTTPS
  • Use [Authorize]
  • Limit payload size
  • Use secure headers
  • Validate all inputs
  • Implement logging & monitoring
Q56:

How do you implement refresh tokens securely?

Junior

Answer

Best practices:

  • Store refresh tokens securely
  • Use rotating refresh tokens
  • Issue short-lived access tokens
  • Revoke tokens on suspicious activity
Q57:

How do you check roles and claims programmatically?

Junior

Answer

Use HttpContext methods:

  • User.IsInRole("Admin")
  • User.Claims to inspect claim values
Q58:

How do you implement custom JWT claims?

Junior

Answer

Add claims during token creation (email, role, custom fields).

Validate claims in controllers or authorization policies.

Q59:

How do you audit API usage for security?

Junior

Answer

Audit using structured logs including:

  • User identity
  • Action invoked
  • Timestamp
  • IP address
  • Request and response metadata

Essential for compliance and threat detection.

Q60:

How do you implement API versioning effectively?

Mid

Answer

API versioning ensures backward compatibility and predictable updates.

Common approaches:

  • URL versioning: /api/v1/resource
  • Query versioning: ?api-version=1.0
  • Header versioning: api-version: 1.0

Use the Microsoft.AspNetCore.Mvc.Versioning package and decorate controllers with [ApiVersion("1.0")].

Q61:

How do you implement compression in Web API?

Mid

Answer

Enable compression using:

services.AddResponseCompression()

Supports Gzip and Brotli to reduce payload size and improve performance.

Q62:

How do you handle exceptions globally?

Mid

Answer

Global exception handling centralizes error responses.

Use:

  • UseExceptionHandler() middleware
  • Custom exception-handling middleware
  • Standardized error payloads and logging
Q63:

What are best practices for structured error responses?

Mid

Answer

Include:

  • statusCode
  • message
  • errors (validation details)
  • traceId

Avoid exposing internal details for security.

Q64:

How do you implement rate limiting / throttling?

Mid

Answer

Use libraries like AspNetCoreRateLimit to:

  • Limit requests per IP or client
  • Protect server from abuse
  • Apply global or endpoint-specific rules
Q65:

How do you handle large payloads efficiently?

Mid

Answer

Use streaming techniques:

  • IFormFile for uploads
  • Avoid full in-memory buffering
  • Enable compression where needed
Q66:

How do you implement conditional requests?

Mid

Answer

Use:

  • ETag
  • Last-Modified
  • If-None-Match or If-Modified-Since

Returns 304 Not Modified when content is unchanged.

Q67:

How do you prevent over-fetching in Web APIs?

Mid

Answer

Use field selection / projection such as:

?fields=name,email

Implement DTOs to avoid returning unnecessary properties.

Q68:

How do you implement HATEOAS in Web API?

Mid

Answer

HATEOAS enriches responses with navigational links.

Example:

Order response may include:

  • self link
  • update link
  • cancel link
Q69:

How do you implement distributed caching?

Mid

Answer

Use:

  • Redis
  • SQL Server distributed cache
  • Memcached

Useful for multi-instance API deployments.

Q70:

How do you secure sensitive data in responses?

Mid

Answer

Avoid sending PII or sensitive fields.

Use DTOs, masking, or encryption.

Always enforce HTTPS.

Q71:

How do you handle versioning breaking changes?

Mid

Answer

Best practices:

  • Maintain old versions
  • Introduce new versioned endpoints
  • Document migration paths
Q72:

How do you implement pagination?

Mid

Answer

Use Skip and Take (LINQ).

Include:

  • page
  • pageSize
  • totalCount
  • totalPages
Q73:

How do you implement filtering and sorting?

Mid

Answer

Expose query parameters for filtering and sorting:

  • ?status=active
  • ?sort=name_desc

Combine with pagination for scalable responses.

Q74:

How do you monitor API performance in production?

Mid

Answer

Use monitoring tools:

  • Application Insights
  • Prometheus + Grafana
  • Serilog

Track duration, throughput, failure rates, response sizes.

Q75:

How do you implement API health checks?

Mid

Answer

Use built-in health checks:

services.AddHealthChecks();

Expose /health endpoint to monitor DB, disk, and external services.

Q76:

How do you maintain backward compatibility while refactoring endpoints?

Mid

Answer

Keep older versions active.

Deprecate API versions gradually.

Provide documentation for migration.

Q77:

How do you implement API documentation effectively?

Mid

Answer

Use Swagger / OpenAPI:

  • Interactive documentation
  • Multiple version support
  • Authentication integration
  • Schema validation
Q78:

How do you integrate Entity Framework Core with Web API?

Mid

Answer

To integrate EF Core with Web API:

  • Install EF Core packages such as Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer.
  • Register your DbContext in Program.cs using AddDbContext.
  • Inject DbContext via constructor injection in controllers or services.
  • Use migrations and LINQ for strongly-typed database access.
Q79:

What is the difference between DbContext and DbSet?

Mid

Answer

DbContext manages the database connection, querying, saving, and tracking of entities.

DbSet<T> represents a table and allows querying and CRUD operations for that entity type.

Q80:

How do you implement DTOs and why?

Mid

Answer

DTOs decouple API contracts from internal entity models.

Benefits:

  • Prevents over-posting
  • Improves security
  • Helps with API versioning
  • Simplifies maintenance

Mapping can be done manually or using AutoMapper.

Q81:

What is the Repository Pattern and why use it?

Mid

Answer

The Repository Pattern abstracts the data access layer.

It provides:

  • Clean separation of concerns
  • Mockable interfaces for testing
  • Consistent CRUD interface
Q82:

How do you implement Unit of Work pattern?

Mid

Answer

The Unit of Work pattern groups operations under one transaction.

DbContext naturally acts as a Unit of Work; calling SaveChangesAsync commits all changes atomically.

Q83:

How do you handle transactions in EF Core?

Mid

Answer

Use explicit transactions via:

await context.Database.BeginTransactionAsync();

Wrap operations in try/catch to commit or rollback.

Q84:

How do you implement asynchronous queries in EF Core?

Mid

Answer

Use async LINQ extensions:

  • ToListAsync()
  • FirstOrDefaultAsync()
  • SingleOrDefaultAsync()

Improves scalability by freeing threads during database I/O.

Q85:

How do you implement filtering and sorting with EF Core?

Mid

Answer

Use LINQ:

  • Where() for filtering
  • OrderBy()/OrderByDescending() for sorting
  • Skip()/Take() for pagination
Q86:

How do you prevent over-posting when updating entities?

Mid

Answer

Use DTOs and map only allowed fields.

Avoid binding client input directly to entity models.

Q87:

How do you implement soft deletes?

Mid

Answer

Add an IsDeleted flag and filter queries:

.Where(x => !x.IsDeleted)

Useful for audits and data recovery.

Q88:

How do you implement optimistic concurrency in EF Core?

Mid

Answer

Use a RowVersion (timestamp) column.

EF detects conflicts and throws DbUpdateConcurrencyException.

Q89:

How do you implement eager, lazy, and explicit loading?

Mid

Answer

Eager: Include()

Lazy: Navigation property auto-loading (requires proxies)

Explicit: context.Entry(entity).Collection(...).Load()

Q90:

How do you handle many-to-many relationships in EF Core?

Mid

Answer

EF Core 5+ supports many-to-many with:

HasMany().WithMany()

Junction table is auto-created unless custom entity is needed.

Q91:

How do you handle transactions across multiple DbContext instances?

Mid

Answer

Use TransactionScope for distributed transactions.

Or share the same database connection among contexts.

Q92:

How do you execute raw SQL queries in EF Core?

Mid

Answer

Use:

  • FromSqlRaw() for queries
  • ExecuteSqlRaw() for commands

Always use parameters to prevent SQL injection.

Q93:

How do you implement caching for database queries?

Mid

Answer

Use:

  • IMemoryCache for local cache
  • Redis for distributed cache

Cache expensive queries and invalidate on updates.

Q94:

How do you implement pagination efficiently in EF Core?

Mid

Answer

Use:

Skip((page-1)*pageSize).Take(pageSize)

Combine with filtering and sorting before applying pagination.

Q95:

How do you handle migrations in EF Core?

Mid

Answer

Use:

  • Add-Migration
  • Update-Database

Supports schema evolution and controlled deployments.

Q96:

How do you manage large datasets in EF Core?

Mid

Answer

Best practices:

  • Use projection via Select()
  • Use pagination
  • Avoid ToList() on large tables
  • Optimize queries with indexes
Q97:

How do you test Web API with EF Core?

Mid

Answer

Testing strategies:

  • Use InMemory provider for unit tests
  • Use SQLite in-memory for integration tests
  • Mock repositories/DbContext for isolation
Q98:

What are common Web API design patterns?

Senior

Answer

Common Web API design patterns improve maintainability, scalability, and testability:

  • Repository Pattern – Abstracts data access; simplifies unit testing and business logic separation.
  • Unit of Work – Groups operations under a single transaction for consistency.
  • CQRS – Separates read and write operations for scalability and performance.
  • Mediator / MediatR – Decouples request-handling logic using command/query handlers.
  • Decorator Pattern – Adds logging, caching, or auditing without modifying core business logic.
Q99:

How do you implement centralized logging?

Senior

Answer

Centralized logging ensures consistent tracking across all API requests.

  • Use ILogger<T> via dependency injection.
  • Capture structured logs with levels (Trace ? Critical).
  • Write logs to console, files, databases, or providers like Seq, ELK, Splunk, or Application Insights.
  • Use middleware to log incoming requests, outgoing responses, and execution duration.
Q100:

How do you implement safe request and response logging?

Senior

Answer

To log request/response bodies safely:

  • Use custom middleware to intercept HTTP pipeline.
  • Enable request buffering using HttpRequest.EnableBuffering().
  • Buffer and copy response streams using a wrapper.
  • Avoid logging sensitive fields such as passwords, tokens, and PII.
  • Include traceId or correlationId for cross-service tracking.
Q101:

How do you implement response caching effectively?

Senior

Answer

Effective caching improves performance and reduces database load:

  • Use the [ResponseCache] attribute for client caching.
  • Use server-side caching middleware for heavy endpoints.
  • Leverage distributed caches like Redis or Memcached for load-balanced apps.
  • Apply cache invalidation strategies to prevent stale data.
Q102:

How do you implement API documentation with Swagger?

Senior

Answer

Swagger/OpenAPI improves discoverability and client integration.

  • Install Swashbuckle.AspNetCore.
  • Configure AddSwaggerGen() in Program.cs.
  • Include XML comments for controllers and models.
  • Support authentication, versioning, schema examples, and UI customization.
Q103:

How do you organize Web API endpoints for large applications?

Senior

Answer

Large-scale APIs require structured endpoint organization:

  • Use feature-based folder structure instead of traditional controller-based.
  • Group routes using /api/v1/[module]/[controller].
  • Use Areas for large domains.
  • Apply consistent naming and versioning strategies.
Q104:

How do you handle unhandled exceptions in asynchronous code?

Senior

Answer

To handle async exceptions:

  • Wrap async operations in try/catch.
  • Ensure thrown exceptions bubble to global exception middleware.
  • Capture structured logs for debugging.
  • Avoid async void except for event handlers.
Q105:

How do you implement health checks?

Senior

Answer

Health checks monitor service and dependency availability.

  • Use Microsoft.Extensions.Diagnostics.HealthChecks.
  • Expose a /health endpoint.
  • Check database connections, external APIs, disk, cache, etc.
  • Integrate with monitoring tools (Kubernetes, Azure, AWS, Prometheus).
Q106:

How do you implement retry policies and resilience?

Expert

Answer

Resilience protects APIs from transient failures and cascading outages:

  • Use Polly for retry, circuit breaker, timeout, fallback, and bulkhead isolation policies.
  • Retry only for safe operations (idempotent GET or PUT).
  • Use exponential backoff and jitter to avoid retry storms.
  • Wrap external API calls, DB operations, and messaging clients with policies.
  • Monitor policy behavior to detect fragile dependencies.
Q107:

How do you implement versioned Swagger documentation?

Expert

Answer

Versioned Swagger ensures clarity when multiple API versions coexist:

  • Configure multiple SwaggerDoc groups in AddSwaggerGen().
  • Use ApiExplorerSettings to group endpoints by version.
  • Apply versioned routes (v1, v2) or header/query-based versioning.
  • Expose separate Swagger UI endpoints for each version.
  • Helps clients migrate safely while maintaining backward compatibility.
Q108:

How do you implement pagination, filtering, and sorting consistently?

Expert

Answer

Consistent querying ensures scalable and predictable API behavior:

  • Use query parameters: page, pageSize, sort, filter.
  • Implement logic in repositories or service layer for maintainability.
  • Combine pagination with filtering and sorting before DB execution.
  • Cache frequently accessed listings for performance.
  • Return metadata: total records, total pages, current page, page size.
Q109:

How do you implement HATEOAS for large APIs?

Expert

Answer

HATEOAS improves API discoverability and client navigation:

  • Embed hypermedia links (self, edit, delete, related resources) in response models.
  • Generate URLs using UrlHelper or route names.
  • Encapsulate link-building logic in DTOs or dedicated services.
  • Useful in large RESTful ecosystems where clients discover workflows dynamically.
Q110:

How do you implement correlation IDs for request tracing?

Expert

Answer

Correlation IDs enable tracking a request across microservices:

  • Generate or read a CorrelationId header in middleware.
  • Pass it to downstream services and logs.
  • Use logging scopes so all log entries share the same ID.
  • Send correlationId in the API response for client troubleshooting.
  • Critical for debugging distributed API flows.
Q111:

How do you compress responses dynamically?

Expert

Answer

Response compression improves performance for large payloads:

  • Enable AddResponseCompression() middleware.
  • Use Gzip or Brotli for optimal compression ratios.
  • Whitelisted MIME types ensure only necessary content is compressed.
  • Compression reduces bandwidth use and improves client response times.
Q112:

How do you test APIs effectively?

Expert

Answer

Effective testing ensures correctness, stability, and performance:

  • Unit test controllers using mocked services (Moq, NSubstitute).
  • Use WebApplicationFactory or TestServer for integration tests.
  • Use Postman/Newman or CI pipelines for end-to-end validation.
  • Validate headers, status codes, responses, and edge cases.
  • Load test APIs using JMeter, k6, or Locust to verify scalability.
Q113:

How do you maintain API backward compatibility?

Expert

Answer

Backward compatibility prevents breaking existing clients:

  • Version APIs instead of modifying existing contracts.
  • Deprecate older versions gradually with communication.
  • Use DTOs to control exposed data without altering entities.
  • Document breaking changes and provide migration guides.
  • Avoid removing fields abruptly; mark them as deprecated first.

Curated Sets for ASP.NET Web API

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice