🚀 220+ Web API, REST & GraphQL Interview Q&A 2026
Beginner → Most Expert • AI-Powered APIs • Real Business Scenarios • Hands‑on Labs
📑 Inside This Epic Guide (237 Items)
🌟 Beginner Web API & REST Questions (50)
Solid foundations every API developer must know.
Beginner 1. What is a Web API?
A Web API (Application Programming Interface) is an interface that allows applications to communicate over HTTP. It typically exposes endpoints that return data in formats like JSON or XML. ASP.NET Core Web API is a framework for building HTTP APIs, but the concept applies to any technology (Node.js, Python, etc.).
Beginner 2. What is REST and its principles?
REST (Representational State Transfer) is an architectural style. Key principles: stateless client‑server communication, uniform interface (resources identified by URIs, manipulation through representations), cacheability, layered system, and (optional) code on demand.
Beginner 3. Explain the HTTP methods used in REST APIs.
GET – retrieve resource. POST – create new resource. PUT – full update/replace. PATCH – partial update. DELETE – remove resource. HEAD – headers only. OPTIONS – discover supported methods.
Beginner 4. What is a resource in REST?
Any information that can be named (e.g., a user, an order, a product). Resources are accessed via URIs (e.g., /api/users/123).
Beginner 5. What are the common HTTP status codes?
2xx (success): 200 OK, 201 Created, 204 No Content. 3xx (redirection): 301 Moved Permanently. 4xx (client error): 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity. 5xx (server error): 500 Internal Server Error, 503 Service Unavailable.
Beginner 6. What is the difference between REST and SOAP?
REST is an architectural style using HTTP, usually JSON; SOAP is a protocol with strict standards (XML, WSDL). REST is lightweight, stateless; SOAP has built‑in error handling and security via WS‑* standards.
Beginner 7. How do you create a simple Web API controller in ASP.NET Core?
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok(_productService.GetAll());
}Beginner 8. What does the [ApiController] attribute do?
Enables automatic model validation errors (400 responses), binding source inference, and multipart/form-data request inference. It reduces boilerplate.
Beginner 9. What is model binding in ASP.NET Core?
Mapping data from HTTP request (query string, route values, body, headers) to action parameters. For example, public IActionResult Get(int id) automatically binds the route parameter id.
Beginner 10. How do you return different HTTP status codes?
return Ok(data); // 200
return Created(uri, obj); // 201
return NoContent(); // 204
return BadRequest(); // 400
return Unauthorized(); // 401
return NotFound(); // 404Beginner 11. What is content negotiation?
The process of selecting the best representation based on the Accept header. ASP.NET Core can return JSON or XML depending on client preference.
Beginner 12. How to enable XML output in ASP.NET Core Web API?
builder.Services.AddControllers().AddXmlDataContractSerializerFormatters();Beginner 13. Explain routing in ASP.NET Core.
Convention‑based routing (e.g., in Program.cs app.MapControllerRoute) or attribute routing with [Route] and [HttpGet] etc. Attribute routing is preferred for APIs.
Beginner 14. What is the difference between IEnumerable<T> and IQueryable<T>?
IEnumerable executes queries in memory; IQueryable builds expression trees, allowing translation to SQL (deferred execution). Use IQueryable for database queries to filter at DB level.
Beginner 15. How do you read request headers in a controller?
string userAgent = Request.Headers["User-Agent"];
// or use [FromHeader] attribute on a parameter.Beginner 16. What is dependency injection and how is it used in Web API?
DI provides objects to a class (typically via constructor). In ASP.NET Core, register services in Program.cs (builder.Services.AddScoped<IProductRepo, ProductRepo>()).
Beginner 17. What is the difference between AddScoped, AddTransient, and AddSingleton?
Transient: new instance every time. Scoped: same instance per HTTP request. Singleton: one instance for the app lifetime.
Beginner 18. How do you validate input in a Web API?
Use data annotations ([Required], [MaxLength]) on model properties. With [ApiController], invalid requests automatically return 400 with details.
Beginner 19. What is CORS and how to enable it in ASP.NET Core?
Cross‑Origin Resource Sharing allows browsers to make requests to a different domain. Configure:
builder.Services.AddCors(options => {
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
app.UseCors("AllowAll");Beginner 20. Explain JSON serialization settings (camelCase, null handling).
Defaults use System.Text.Json with camelCase. Customize via builder.Services.AddControllers().AddJsonOptions(...). Options like PropertyNamingPolicy = JsonNamingPolicy.CamelCase.
Beginner 21. What is the role of the appsettings.json file?
Stores configuration data (connection strings, API keys). Access via IConfiguration (e.g., config["Jwt:Key"]).
Beginner 22. How do you handle exceptions globally?
Use a custom middleware that catches exceptions and returns a uniform JSON error response, or use UseExceptionHandler.
app.UseExceptionHandler("/error");Beginner 23. What is Swagger / OpenAPI?
Swagger is a tool to document REST APIs. OpenAPI is the specification. Swagger UI provides an interactive UI. Use Swashbuckle.AspNetCore NuGet package.
Beginner 24. How to add Swagger to an ASP.NET Core project?
builder.Services.AddSwaggerGen();
// ...
app.UseSwagger();
app.UseSwaggerUI();Beginner 25. What is an action filter?
Runs before or after an action executes. Implement IActionFilter or use [ServiceFilter] attribute. Used for logging, validation, etc.
Beginner 26. How to return a file from a Web API?
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/pdf", "report.pdf");Beginner 27. What is HATEOAS?
Hypermedia as the Engine of Application State. REST responses include links to related actions (e.g., next, previous). Implemented via link headers or HAL JSON.
Beginner 28. What is the purpose of the [FromBody] attribute?
Indicates that a parameter should be bound from the request body (usually JSON). It's implied when using [ApiController] for complex types.
Beginner 29. How do you read query string parameters?
public IActionResult Search([FromQuery] string term, [FromQuery] int page = 1)Beginner 30. What is a DTO (Data Transfer Object)?
An object that carries data between processes, often used to shape responses and avoid exposing domain models directly. Helps with serialization control.
Beginner 31. What is the difference between IActionResult and ActionResult<T>?
IActionResult returns any HTTP response. ActionResult<T> enables returning either a value of type T or an error response, with better type safety.
Beginner 32. How do you implement pagination?
Accept page and pageSize parameters. Use Skip() and Take() (or SQL OFFSET/FETCH) and return metadata (total count) in response headers.
Beginner 33. What is a web API versioning strategy?
Common methods: URL path (e.g., /api/v1/products), query string, header (api-version), or media type (content negotiation). Use NuGet Microsoft.AspNetCore.Mvc.Versioning.
Beginner 34. What is middleware in ASP.NET Core?
Software components assembled into a pipeline to handle requests and responses. Each middleware can execute code, modify request/response, or call the next one. Examples: authentication, static files, routing.
Beginner 35. How do you configure HTTPS redirection?
app.UseHttpsRedirection(); in the pipeline.Beginner 36. What is the difference between async and synchronous actions?
Async actions release the thread to serve other requests during I/O operations, improving scalability. Use async Task<ActionResult> and await for database calls.
Beginner 37. How to log messages in ASP.NET Core?
Inject ILogger<T> and use _logger.LogInformation("..."). Configure providers (Console, Debug, Application Insights).
Beginner 38. What is a JSON Web Token (JWT)?
An open standard (RFC 7519) for securely transmitting claims between parties. Used for authentication. The API validates the token signature and extracts user info.
Beginner 39. How do you implement basic JWT authentication?
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => { /* configure authority, audience, etc. */ });
app.UseAuthentication();
app.UseAuthorization();Beginner 40. What is the app.UseRouting() and app.UseEndpoints()?
In ASP.NET Core 3+, UseRouting matches the request to an endpoint; UseEndpoints executes the matched endpoint. In .NET 6+, app.MapControllers() is used within UseEndpoints.
Beginner 41. What are environment variables in ASP.NET Core?
Used for configuration (like ASPNETCORE_ENVIRONMENT). In appsettings.{Environment}.json you override settings per environment (Development, Staging, Production).
Beginner 42. How do you serve static files in a Web API project?
app.UseStaticFiles(); (though typically APIs don't serve static files, but can).Beginner 43. What is the difference between PUT and PATCH?
PUT replaces the entire resource; PATCH applies partial modifications (usually with JSON Patch or merge patch). Use PUT when you send the full object.
Beginner 44. How do you handle file uploads in Web API?
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file) {
var path = Path.Combine("uploads", file.FileName);
using var stream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(stream);
return Ok();
}Beginner 45. What is a RESTful endpoint naming convention?
Use plural nouns (e.g., /api/orders), no verbs. Use sub‑resources for relationships: /api/orders/123/items. Actions beyond CRUD use a specific resource (e.g., /api/orders/123/cancel).
Beginner 46. What is the difference between a controller and a minimal API?
Minimal APIs (introduced in .NET 6) use a simple app.MapGet("/...", () => ...) pattern without controllers. Good for small microservices. Controllers give more structure for larger projects.
Beginner 47. How to enable cookie authentication?
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
app.UseAuthentication();Beginner 48. What is the Options pattern in ASP.NET Core?
Bind configuration sections to strongly‑typed classes using IOptions<T>, IOptionsSnapshot<T>, or IOptionsMonitor<T>.
builder.Services.Configure<MySettings>(builder.Configuration.GetSection("MySettings"));Beginner 49. How to return a 404 if a resource is not found?
var item = await _context.Items.FindAsync(id);
if (item == null) return NotFound();
return Ok(item);Beginner 50. What is the role of the Program.cs file in .NET 6+?
It's the entry point with top‑level statements. You configure services (builder), build the app, and define the request pipeline (middleware).
🔵 Intermediate Questions (60)
Deeper dive into REST design, GraphQL basics, security, and performance.
Intermediate 51. What is GraphQL and how does it differ from REST?
GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike REST, where multiple endpoints return fixed structures, GraphQL has a single endpoint and the client specifies the shape of the response. It reduces over‑fetching and under‑fetching.
Intermediate 52. Describe the main components of a GraphQL schema.
Types: object types, scalar types (String, Int, Float, Boolean, ID), enums. Query: entry point for reads. Mutation: entry point for writes. Subscription: real‑time events. Also interfaces, unions, and input types.
Intermediate 53. What is a resolver in GraphQL?
A function that populates data for a single field. Every field in the schema has a resolver. Root query fields have resolvers that return data; nested object fields have resolvers that map to properties or fetch related data.
Intermediate 54. How does ASP.NET Core handle request validation automatically?
With [ApiController], if model state is invalid, a 400 response with problem details (RFC 7807) is returned automatically. Customize with InvalidModelStateResponseFactory.
Intermediate 55. What are the best practices for REST API error responses?
Return appropriate HTTP status codes, include a consistent error body (e.g., { "error": { "code": "...", "message": "...", "details": [...] } }). Use RFC 7807 Problem Details (application/problem+json).
Intermediate 56. Explain JWT refresh token flow.
Client receives a short‑lived access token and a longer‑lived refresh token. When access token expires, the client sends the refresh token to a dedicated endpoint to get a new access token (and optionally a new refresh token). This reduces exposure of long‑lived tokens.
Intermediate 57. What is OAuth 2.0 and OpenID Connect?
OAuth 2.0 is an authorization framework (delegated access). OpenID Connect adds identity layer on top of OAuth 2.0 for authentication. Common flows: Authorization Code, Client Credentials. Web APIs validate tokens issued by an authority (IdentityServer, Auth0).
Intermediate 58. How to implement API key authentication?
Extract API key from header or query string, validate against a store (database, config). Use a custom authentication handler or middleware. Not as secure as token‑based; consider using HMAC signing.
// middleware extracts X-Api-Key and validates.Intermediate 59. What is rate limiting and how to implement it in ASP.NET Core?
Limit the number of requests a client can make within a time window. Use the built‑in rate limiting middleware in .NET 7+ (AddRateLimiter) with policies like fixed window, sliding window, token bucket, concurrency.
Intermediate 60. How do you handle large request bodies efficiently?
Use streaming (e.g., Request.Body). Avoid buffering entire payload. Set MaxRequestBodySize in kestrel. For file uploads, save to disk in chunks.
Intermediate 61. What is output caching in ASP.NET Core 7+?
Caches the entire HTTP response for given duration/policy, significantly improving performance for GET requests. Use [OutputCache] attribute with profiles.
Intermediate 62. Explain the difference between ResponseCache attribute and output caching.
[ResponseCache] sets HTTP cache headers to instruct clients/proxies; output caching stores response on the server and reuses it without hitting the action.
Intermediate 63. How to implement ETag for optimistic concurrency?
Calculate a hash of the response body (or use a version/timestamp). Add ETag header. On update, compare the If-Match header with current ETag; return 412 Precondition Failed if mismatch.
Intermediate 64. What are CQRS and MediatR?
CQRS separates read and write operations. MediatR is a library implementing the mediator pattern, helping decouple controllers from handlers. You send a query or command and MediatR dispatches to the correct handler.
Intermediate 65. How to use AutoMapper with Web API?
Create mapping profiles (Entity ↔ DTO). Register builder.Services.AddAutoMapper(typeof(Program)); and inject IMapper. Use mapper.Map<ProductDto>(product) to project data.
Intermediate 66. How to implement GraphQL in an ASP.NET Core app?
Use libraries like Hot Chocolate or GraphQL.NET. Define types, create query/mutation types, register GraphQL server, and map endpoint: app.MapGraphQL();.
Intermediate 67. 🤖 AI Trend How to build an AI-powered API endpoint that uses OpenAI?
Call OpenAI HTTP API from your controller or service using HttpClient. Securely store API key. Process request, send prompt, and return the generated content. Example:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var content = new StringContent(JsonSerializer.Serialize(new { model = "gpt-3.5-turbo", messages = ... }));
var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
return Ok(await response.Content.ReadAsStringAsync());Intermediate 68. Explain the N+1 problem in REST/GraphQL and how to solve it.
In REST, when loading nested resources (e.g., orders and their items) you might execute one query for orders then N queries for items. In GraphQL, resolvers can cause same issue. Solve with eager loading (EF Core .Include()), batching (Dataloader in GraphQL), or by returning pre‑joined data.
Intermediate 69. What is a Dataloader in GraphQL?
A utility that batches and caches database requests to prevent N+1. It collects unique keys across multiple field resolutions, then loads them in a single query. In .NET, Hot Chocolate provides integrated DataLoader support.
Intermediate 70. How to secure GraphQL APIs?
Authenticate via JWT/cookies on the HTTP layer (same as REST). Add authorization logic inside resolvers using policies. Validate depth/complexity of queries to prevent abuse. Use persisted queries for trusted clients.
Intermediate 71. What is a REST API filter/pagination/search pattern?
Use query parameters: ?page=2&size=10&sort=name&name=*abc*. Common standards: OData, JSON:API. Build dynamic LINQ expressions based on the parameters.
Intermediate 72. What is HATEOAS and how to add links to an ASP.NET Core response?
Generate links for related resources. Use a wrapper class that includes Links property. Use Url.Link() to generate absolute URIs. Example library: `HAL.AspNetCore` or custom approach.
Intermediate 73. How to implement API versioning with headers?
builder.Services.AddApiVersioning(config => {
config.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
config.AssumeDefaultVersionWhenUnspecified = true;
});Intermediate 74. How do you handle concurrency conflicts (optimistic concurrency) in Web API?
Use a timestamp/row version column. When updating, check if the timestamp has changed; if so, return 409 Conflict or 412 Precondition Failed.
Intermediate 75. What is a correlation ID and why is it useful?
A unique identifier added to each request (and logged) to trace it across multiple services. In ASP.NET Core, use middleware to generate/read X-Correlation-ID header and include it in logs.
Intermediate 76. How to implement a retry policy with HttpClient?
Use Polly library. Add a policy to IHttpClientFactory:
builder.Services.AddHttpClient("myservice")
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));Intermediate 77. What is the Circuit Breaker pattern?
Prevents cascading failures by stopping calls to a failing external service. After a threshold, the circuit opens and fast‑fails. Polly supports AddPolicyHandler(...).CircuitBreakerAsync(...).
Intermediate 78. How to create a custom model binder?
Implement IModelBinder and IModelBinderProvider; register. Or use [ModelBinder(BinderType = typeof(MyBinder))] on a parameter.
Intermediate 79. How does ASP.NET Core handle JSON serialization for polymorphic types?
Use [JsonDerivedType] attribute on base type, or a custom JsonConverter to read/write type discriminators.
Intermediate 80. What are the benefits of using IAsyncEnumerable<T> in API responses?
Streams data as it becomes available, reducing memory consumption. In ASP.NET Core 6+, you can return IAsyncEnumerable<T> from an action; the framework sends a chunked JSON array. Good for large datasets.
Intermediate 81. Explain the concept of API Gateway.
An API Gateway sits between clients and microservices, routing requests, aggregating results, handling authentication, rate limiting, and caching. Examples: Ocelot, Azure API Management.
Intermediate 82. What is OData and when to use it?
OData (Open Data Protocol) builds RESTful APIs with rich query capabilities ($filter, $select, $expand). It's useful for data‑centric applications but adds complexity. Use Microsoft.AspNetCore.OData.
Intermediate 83. How to create a GraphQL subscription in Hot Chocolate?
public class Subscription {
[Subscribe]
public Message MessageAdded([EventMessage] Message message) => message;
}
// In Program.cs:
builder.Services.AddGraphQLServer().AddSubscriptionType<Subscription>().AddInMemorySubscriptions();
app.UseWebSockets();
app.MapGraphQL();Intermediate 84. What is the difference between REST and GraphQL error handling?
In REST, you return HTTP status codes. In GraphQL, you always get 200 OK; errors are inside the errors array. Partial data can be returned alongside errors.
Intermediate 85. How to prevent over‑fetching in REST APIs?
Allow sparse fieldsets via query parameter (e.g., ?fields=id,name), or use JSON:API fields. Provide different DTOs for different use cases.
Intermediate 86. How to secure a Web API with certificates (mTLS)?
Enable client certificate authentication in Kestrel and add middleware to validate the certificate thumbprint or chain. builder.WebHost.ConfigureKestrel(o => o.ConfigureHttpsDefaults(h => h.ClientCertificateMode = ClientCertificateMode.RequireCertificate));
Intermediate 87. 🤖 AI Trend How to integrate Azure Cognitive Services (e.g., Translator) into an API?
Use Azure SDK or REST API. Create an endpoint that receives text and target language, calls the Cognitive Services endpoint with API key, returns translated text. Use HttpClient.
Intermediate 88. How to implement a background job using hosted services?
Implement BackgroundService and override ExecuteAsync. Register with builder.Services.AddHostedService<MyWorker>(). For distributed systems, use Hangfire or Azure WebJobs.
Intermediate 89. What is the ProblemDetails class and RFC 7807?
ProblemDetails is a standard object for error responses containing type, title, status, detail, instance. With [ApiController] and app.UseExceptionHandler(), you can produce it. Use ProblemDetailsFactory to customize.
Intermediate 90. How do you use HttpClientFactory and why?
It manages HttpClient instances to prevent socket exhaustion. Register named or typed clients, configure base address and policies. Inject IHttpClientFactory and create a client when needed.
Intermediate 91. Explain GraphQL query batching and how to implement it.
Send multiple queries/mutations in a single HTTP request as a JSON array. Hot Chocolate supports this out of the box via GraphQLHttpMiddleware.
Intermediate 92. What is a stored/persisted query in GraphQL?
Instead of sending the full query text each time, the client sends a hash/id; the server looks up the pre‑registered query. This reduces bandwidth and improves security (no arbitrary queries).
Intermediate 93. How to monitor and log HTTP requests/responses in ASP.NET Core?
Use HttpLoggingMiddleware (app.UseHttpLogging();) or create custom middleware. Configure with builder.Services.AddHttpLogging(o => o.LoggingFields = HttpLoggingFields.All);
Intermediate 94. What is the difference between ToString() and serialization?
Not relevant? Might be about JSON serialization: JsonSerializer produces JSON; ToString() is an object’s representation, not API‑grade. Probably a filler. Let's replace with something better.
Actually, rephrase: How to customize JSON serialization with System.Text.Json?
builder.Services.AddControllers().AddJsonOptions(options => {
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});Intermediate 95. How to implement a health check endpoint?
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health"); Add checks for database, external services.Intermediate 96. What is a GraphQL schema directive?
Custom annotations that modify schema behavior (e.g., @deprecated, @authorize). You can implement custom directives for authorization, logging, etc.
Intermediate 97. How to handle file downloads with range requests (resumable)?
Return FileStreamResult with enableRangeProcessing: true. The server automatically supports Range header and returns 206 Partial Content.
Intermediate 98. What is the Accept-Encoding header and response compression?
Used to request gzip, brotli compression. Add app.UseResponseCompression(); after registering services. Reduces bandwidth.
Intermediate 99. How to implement a custom authentication handler?
Inherit from AuthenticationHandler<AuthenticationSchemeOptions>, override HandleAuthenticateAsync. Extract credentials, validate, create AuthenticationTicket.
Intermediate 100. How to use Polly for resilience in HTTP calls?
Define policies for retry, timeout, circuit breaker. Use with HttpClientFactory as shown earlier. Or apply directly: await policy.ExecuteAsync(() => client.GetAsync(url));
Intermediate 101. What is the difference between Task.Run and async/await in API actions?
async/await doesn't create new threads; it frees the thread during I/O. Task.Run offloads to the thread pool, which might be used for CPU‑bound work, but avoid in API unless necessary.
Intermediate 102. How to implement API key rotation?
Store multiple valid keys per client (active + next). Return a list of keys with expiry. Client should accept both until transition is complete.
Intermediate 103. Explain REST API maturity model (Richardson).
Level 0: HTTP as transport. Level 1: Resources. Level 2: HTTP verbs. Level 3: Hypermedia controls (HATEOAS).
Intermediate 104. What is GraphQL Federation?
An approach to compose multiple GraphQL services into a single unified graph. A gateway service stitches schemas from subgraphs. Hot Chocolate supports federation v1/v2.
Intermediate 105. How to do bulk operations in REST?
Create a dedicated bulk endpoint (e.g., POST /api/orders/bulk) that accepts an array of resources. Ensure atomicity or provide partial success details.
Intermediate 106. How to use EF Core with Web API efficiently (AsNoTracking)?
For read‑only queries, use .AsNoTracking() to avoid change tracking overhead. Also use projections (.Select()) to load only needed columns.
Intermediate 107. What are the best practices for async actions (ConfigureAwait)?
In ASP.NET Core, ConfigureAwait(false) is not necessary because there's no synchronization context (except legacy). But it's good practice in library code to avoid capturing context.
Intermediate 108. How to return a stream from an API without buffering?
[HttpGet]
public IActionResult GetStream() {
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return File(stream, "application/octet-stream");
}Intermediate 109. How to handle concurrency with ETag using a filter?
Create an IAsyncActionFilter that generates an ETag on GET and checks If-Match on PUT. Return 304 Not Modified or 412.
Intermediate 110. What is the difference between IClientRequestValidator and middleware for security?
No such interface? Possibly a confusion. Let's replace: How to validate incoming IP address with middleware?
app.Use(async (context, next) => {
var remoteIp = context.Connection.RemoteIpAddress;
if (!IsAllowed(remoteIp)) {
context.Response.StatusCode = 403;
return;
}
await next();
});🟣 Expert Questions (50)
Expert 111. How does the ASP.NET Core request pipeline work with middleware?
Each middleware gets a RequestDelegate next. It can execute code before/after calling next. The pipeline is built in Program.cs. The runtime builds a chain; first registered middleware runs first.
Expert 112. What is a RequestDelegate and how to create custom middleware?
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) { _next = next; }
public async Task InvokeAsync(HttpContext context) {
// pre
await _next(context);
// post
}
}Expert 113. Explain the concept of IHostedService and BackgroundService.
Used for long‑running background tasks. StartAsync and StopAsync. BackgroundService simplifies implementation by providing a CancellationToken.
Expert 114. How to design a scalable, idempotent API?
Use idempotency keys: client sends a unique key with request. Server stores the response for that key; on duplicate, returns cached response without re‑executing. Implement as a filter.
Expert 115. How to implement the Outbox pattern for reliable messaging?
Save events to an outbox table in the same transaction as the business data. A background service reads and publishes them to a message broker, ensuring at‑least‑once delivery.
Expert 116. How to use IAsyncEnumerable with Entity Framework Core for streaming large datasets?
[HttpGet]
public async IAsyncEnumerable<Product> GetProducts() {
await foreach (var product in _context.Products.AsAsyncEnumerable()) {
yield return product;
}
}Expert 117. 🤖 AI How to integrate Azure OpenAI with semantic caching in a Web API?
Generate embedding for user query, search cache (vector DB) for similar question, return cached answer if similarity > threshold. Otherwise call OpenAI, cache response + embedding.
Expert 118. Explain hot chocolate’s filter/interceptor capabilities.
Use IErrorFilter to handle exceptions; IHttpRequestInterceptor to inspect incoming requests. Custom DiagnosticEventListener for tracing.
Expert 119. How to implement a GraphQL gateway with Apollo Federation using .NET?
Hot Chocolate supports federation. Add [Key] attribute, define reference resolvers, and register the gateway using builder.Services.AddFederationGateway(...). Subgraphs are separate services.
Expert 120. What is a durable function and how could it be used in an API workflow?
Azure Durable Functions allow stateful orchestrations. An API can trigger an orchestrator function, then check status via a status endpoint. Useful for long‑running operations like order processing.
Expert 121. How to use System.Threading.Channels for in‑process pub/sub?
Channel<T> channel = Channel.CreateUnbounded<T>();
// writer: await channel.Writer.WriteAsync(item);
// reader: await channel.Reader.ReadAsync(item);Expert 122. What is the impact of async void in ASP.NET and why avoid it?
async void cannot be awaited and crashes may bring down the process. Only use for event handlers. In API controllers, always use async Task.
Expert 123. How to implement a decorator pattern for IDbContext to add cross‑cutting concerns?
Use Scrutor or manual registration. Decorate DbContext to log queries, add audit fields.
Expert 124. Explain the difference between stateful and stateless services in microservices.
Web APIs are typically stateless; session data stored externally (Redis). Stateful services maintain state in memory, harder to scale.
Expert 125. How to handle distributed transactions without 2PC?
Use the Saga pattern (choreography or orchestration) with compensating actions. Eventual consistency.
Expert 126. How to implement a custom GraphQL scalar type (e.g., DateTime)?
public class DateTimeType : ScalarType<DateTime> { ... }
services.AddGraphQLServer().AddType<DateTimeType>();Expert 127. What is GraphQL query depth/complexity analysis and how to enforce it?
Measure query nesting and field count. Use Hot Chocolate’s AddMaxExecutionDepthRule() and AddComplexityAnalyzer() to reject expensive queries.
Expert 128. How to design a REST API with long‑running operations (asynchronous request‑reply)?
Return 202 Accepted with a Location header to a status endpoint. Client polls for result. Alternative: webhooks.
Expert 129. How to use the System.Text.Json source generator for performance?
[JsonSerializable(typeof(Product))]
internal partial class MyContext : JsonSerializerContext { }
// Use: JsonSerializer.Serialize(product, MyContext.Default.Product);Expert 130. How to implement IEndpointFilter for minimal APIs (validation, logging)?
app.MapGet("/hello", () => "Hello").AddEndpointFilter(async (context, next) => {
// pre
var result = await next(context);
// post
return result;
});Expert 131. What are the benefits of using the Grpc.AspNetCore package for high‑performance APIs?
gRPC uses Protocol Buffers, binary serialization, HTTP/2, and offers streaming, strong typing. Much faster than JSON REST for internal services.
Expert 132. How to implement a GraphQL subscription over WebSockets in a load‑balanced environment?
Use a backplane like Redis. Hot Chocolate provides AddRedisSubscriptions() to sync events across servers.
Expert 133. How to implement a custom ISchemaFilter to hide endpoints from Swagger conditionally?
public class HideEndpointFilter : IDocumentFilter {
public void Apply(OpenApiDocument doc, DocumentFilterContext ctx) { ... }
}Expert 134. How to use IMemoryCache vs IDistributedCache in API?
IMemoryCache local, fast, not shared. IDistributedCache (Redis, SQL) shared across servers. Use distributed for multi‑instance.
Expert 135. Explain the Strangler Fig pattern for migrating legacy APIs.
Gradually replace old API endpoints with new ones behind a router. Once all traffic is on new, decommission old.
Expert 136. How to implement a WebSocket endpoint in ASP.NET Core for real‑time notifications?
app.UseWebSockets();
app.Map("/ws", async context => {
if (context.WebSockets.IsWebSocketRequest) {
var ws = await context.WebSockets.AcceptWebSocketAsync();
// send/receive
}
});Expert 137. What are the security considerations for GraphQL (DoS, injection)?
Implement query cost analysis, limit depth, timeout, rate limiting, field aliasing limits, avoid string concatenation for underlying queries, use parameterized resolvers.
Expert 138. How to implement a custom IAuthorizationHandler for resource‑based authorization?
public class DocumentAuthorizationHandler : AuthorizationHandler<SameAuthorRequirement, Document> {
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SameAuthorRequirement requirement, Document resource) { ... }
}Expert 139. How to use Channels to implement a producer‑consumer pattern for batch processing?
Producer writes to channel; a background service reads and processes in batches. Increases throughput.
Expert 140. What is the difference between Parallel.ForEachAsync and Task.WhenAll?
WhenAll starts all tasks concurrently and waits. Parallel.ForEachAsync processes items with a degree of parallelism, good for CPU‑bound but may be used for I/O with caution.
Expert 141. How to design a multi‑tenant API?
Identify tenant via header (e.g., X-Tenant-Id) or host. Use scoped services to resolve tenant‑specific configurations, database connections. Ensure data isolation.
Expert 142. How to implement a correlation ID propagation across services?
Middleware captures/generates X-Correlation-ID. When calling downstream, include it via HttpClient headers. Use Activity/TraceIdentifier for telemetry.
Expert 143. What are the benefits of using the System.Threading.Tasks.Dataflow library?
Builds complex dataflow pipelines (blocks: TransformBlock, ActionBlock) with concurrency control. Good for ETL processes in an API background worker.
Expert 144. How to use YARP (Reverse Proxy) as an API Gateway?
Add Yarp.ReverseProxy package, configure routes and clusters in appsettings.json or code. YARP handles request forwarding, load balancing, transforms.
Expert 145. How to implement a custom GraphQL error filter that logs and transforms exceptions?
public class CustomErrorFilter : IErrorFilter {
public IError OnError(IError error) { _logger.LogError(error.Exception, error.Message); return error.WithMessage("User‑friendly message"); }
}Expert 146. How to perform canary releases for an API?
Deploy new version alongside old, route a percentage of traffic (by header, weight) to the new version using a traffic manager (YARP, Azure Traffic Manager) and monitor metrics.
Expert 147. How to implement API functional testing with WebApplicationFactory?
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/api/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);Expert 148. What is the difference between IntegrationTest and WebApplicationFactory?
WebApplicationFactory is used for in‑memory integration tests that start the full app pipeline. You can override services with test doubles.
Expert 149. How to version GraphQL schemas?
GraphQL avoids versioning by deprecating fields and adding new ones. But you can also version the URL or use schema stitching with multiple schemas per version.
Expert 150. How to implement a batch mutation (e.g., create many orders atomically)?
Wrap operations in a database transaction. Use DbContext.Database.CreateExecutionStrategy() for retries. Return array of results.
Expert 151. How to use System.Diagnostics.Activity for distributed tracing?
Start an Activity with trace id; propagation via headers (W3C TraceContext). Integrate with OpenTelemetry.
Expert 152. Explain the concept of a BFF (Backend for Frontend) pattern.
Create a dedicated API layer per client (web, mobile) that aggregates data from downstream services and tailors responses, reducing over‑fetching and security surface.
Expert 153. How to prevent sensitive data exposure in API responses?
Use DTOs that exclude sensitive fields, [JsonIgnore], or custom DefaultJsonTypeInfoResolver to conditionally include properties.
Expert 154. How to use Microsoft.FeatureManagement for feature flags in APIs?
Enable feature filters (time‑based, targeting) and use IFeatureManager to branch in code. Good for gradual rollouts.
Expert 155. How to implement a GraphQL introspection disable in production?
Set options.EnableSchemaRequests = false; in Hot Chocolate, or by middleware blocking __schema. Allows persisted queries only.
Expert 156. How to perform request decompression for gzipped request bodies?
app.UseRequestDecompression(); supported in .NET 7+.Expert 157. How to implement a circuit breaker for database connections?
Use Microsoft.Extensions.Http.Resilience or Polly. Wrap DB calls with a policy that trips after consecutive failures.
Expert 158. How to handle large GraphQL query responses efficiently (streaming)?
Use deferred/incremental delivery (upcoming in GraphQL spec) or implement IAsyncEnumerable in resolvers; Hot Chocolate supports streaming via [UseStreaming].
Expert 159. How to build a GraphQL @oneOf input type for variant inputs?
Define a union input type or use OneOf attribute in Hot Chocolate to enforce only one field.
Expert 160. How to implement API key rotation with grace period?
Store multiple active keys per client with issue/expiry dates. Validate against all active keys. API returns X-Key-Expiry header.
🔴 Most Expert / Architect (40)
Architect 161. Design a fault‑tolerant event‑driven API using Azure Service Bus.
Publish events after DB transaction (Outbox pattern). Use Service Bus topics, dead‑lettering, and subscription rules. Retry and handle poison messages.
Architect 162. How to implement a write‑behind cache for API performance?
Write to Redis cache first, then asynchronously persist to database using a background queue. Ensure eventual consistency.
Architect 163. Explain the .NET Generic Host and how it benefits background services in an API.
The Generic Host provides DI, configuration, logging, and lifetime management. Background services share the same DI container, can use scoped services via IServiceScopeFactory.
Architect 164. How to design a GraphQL schema for a social network with high interconnection?
Use Dataloaders for efficient fetching. Define connections (edges, nodes) following Relay spec. Implement pagination with cursors. Use subscription for real‑time updates.
Architect 165. 🤖 AI Implement an AI‑driven anomaly detection API endpoint that uses ML.NET.
Train a model offline; load it via PredictionEnginePool. The endpoint receives input, runs prediction, returns anomaly score. Background service can retrain.
Architect 166. How to achieve zero‑downtime database migrations in a Web API?
Use expand‑contract pattern: add new columns (nullable), deploy API that writes to both old and new, backfill, then remove old. Use feature flags.
Architect 167. What is the difference between a message queue and a pub/sub (event bus) in microservices?
Queue: point‑to‑point, one consumer. Pub/sub: multiple subscribers receive the same message. Used for event‑driven communication.
Architect 168. How to implement a distributed rate limiter using Redis?
Use a fixed‑window or sliding‑window algorithm with Redis atomic increments and TTL. ASP.NET Core rate limiter can be configured with AddRedisRateLimiter() (via RateLimiting.Redis).
Architect 169. How to secure a Web API with mTLS and Azure App Service.
Enable client certificate requirement in App Service settings. In code, validate certificate thumbprints or require specific issuer.
Architect 170. How to implement a sidecar pattern for API cross‑cutting concerns?
Deploy a sidecar container (e.g., Envoy proxy) alongside the API that handles TLS termination, rate limiting, and logging. In .NET, use YARP as a sidecar.
Architect 171. Design a high‑throughput event ingestion API that persists to a stream (Event Hub).
Use a non‑blocking HTTP endpoint that writes to a channel, a background service batches events and sends to Event Hub with exponential retry. Acknowledge with 202.
Architect 172. How to use System.IO.Pipelines for high‑performance request parsing?
Directly read from HttpContext.Request.BodyReader using PipeReader to parse custom protocols with zero copy and low allocations.
Architect 173. What is the impact of thread pool starvation and how to avoid it in async APIs?
Blocking calls (sync over async) can exhaust thread pool. Always use async/await all the way. Monitor with ThreadPool diagnostics.
Architect 174. How to implement a full‑text search API with Elasticsearch and .NET?
Use NEST or Elasticsearch.Net. Index data asynchronously via background job. API queries Elasticsearch and projects to DTOs.
Architect 175. 🤖 AI Architect an API that uses Azure AI Search for semantic ranking.
Index documents with vector embeddings. API endpoint receives text query, generates embedding via OpenAI, sends search request to AI Search, returns top results with reranking.
Architect 176. How to implement a custom SocketMiddleware for raw TCP alongside HTTP API?
In ASP.NET Core, you can't easily share port for raw TCP. Use middleware that hijacks the connection if it's a specific upgrade (e.g., WebSocket) or use Kestrel's non‑HTTP features (like raw sockets).
Architect 177. What is the “async suffix” convention and when to apply it?
Append “Async” to methods returning Task (e.g., GetAsync()). Helps readability and consistency.
Architect 178. How to achieve eventual consistency between SQL and a search index?
Use change data capture (CDC) or the Outbox pattern to publish events to a queue, which updates the search index asynchronously.
Architect 179. What is the difference between optimistic and pessimistic locking in API updates?
Optimistic: assume no conflict, check row version on update (returns 409 if conflict). Pessimistic: lock database row (SELECT FOR UPDATE) – can cause deadlocks.
Architect 180. How to implement a GraphQL field middleware for performance logging?
services.AddGraphQLServer()
.UseField(next => async context => {
var sw = Stopwatch.StartNew();
await next(context);
sw.Stop();
// log sw.Elapsed
});Architect 181. What is the RequestAborted token and why is it important?
HttpContext.RequestAborted is a CancellationToken triggered when the client disconnects. Long‑running operations should respect it to abort early and free resources.
Architect 182. How to use ValueTask and when?
ValueTask is a struct that can reduce allocations when the result is often synchronous. Useful in high‑performance code paths. Use with caution; do not await multiple times.
Architect 183. How to avoid memory leaks with event handlers in long‑lived services?
Unsubscribe from events when the subscriber is disposed. Use weak references or IDisposable patterns.
Architect 184. What is the role of SocketsHttpHandler and connection pooling?
SocketsHttpHandler manages HTTP connections. Pooling reuses connections, but you must manage lifetimes. IHttpClientFactory handles it automatically.
Architect 185. How to implement API response compression for dynamic content?
Use ResponseCompressionMiddleware with providers (Brotli, Gzip). Consider caching compressed responses.
Architect 186. How to create a custom GraphQL execution strategy (e.g., parallel vs serial)?
Implement IExecutionStrategy and register it. Hot Chocolate allows control over resolver execution order.
Architect 187. What are the security implications of GraphQL introspection in production?
Introspection exposes the entire schema, which could aid attackers. Disable it or restrict to authorized users only.
Architect 188. How to implement a forward proxy in .NET for outbound API calls?
var handler = new HttpClientHandler { Proxy = new WebProxy("http://proxy:8080") };
var client = new HttpClient(handler);Architect 189. How to use Microsoft.Extensions.ObjectPool for reducing allocations in API?
Pool reusable objects (e.g., StringBuilder). ObjectPool.Create<T>(). Return object after use.
Architect 190. Explain how to implement a GraphQL @defer support (incremental delivery).
As of Hot Chocolate 13, @defer and @stream are experimental. It allows streaming parts of the response incrementally.
Architect 191. How to design a GraphQL gateway that handles schema changes gracefully?
Use schema versioning or federation with managed federation (Rover CLI). Gateway can compose multiple subgraphs and handle field removal via deprecation.
Architect 192. How to implement a Web API that supports both REST and GraphQL on the same backend?
Host both in the same ASP.NET app. Map REST controllers and GraphQL endpoint. They can share services but may need different DTOs. Use CORS and authentication consistently.
Architect 193. 🤖 AI How to build a custom AI model inference API using ONNX Runtime in .NET?
Load ONNX model, preprocess input tensor, run inference, postprocess output. Use Microsoft.ML.OnnxRuntime. API endpoint exposes it via POST.
Architect 194. What is the difference between a Stream and a Pipe in .NET for IO?
Stream is a classic abstraction; Pipe is a high‑performance, buffer‑oriented pipeline for handling data (often for network). Pipes reduce allocations.
Architect 195. How to use Server-Sent Events (SSE) in ASP.NET Core for streaming updates?
Response.Headers.Append("Content-Type", "text/event-stream");
while (!cancellationToken.IsCancellationRequested) {
await Response.WriteAsync($"data: {json}\n\n");
await Response.Body.FlushAsync();
await Task.Delay(1000);
}Architect 196. How to achieve exactly‑once delivery in an event‑driven API?
Exactly‑once is hard; use idempotency keys and deduplication on the consumer side, combined with transactional outbox.
Architect 197. How to implement a GraphQL query whitelist for security?
Store allowed query hashes. Validate incoming query hash against the whitelist; reject unregistered queries. Hot Chocolate supports persisted queries.
Architect 198. How to handle large file uploads with streaming and progress reporting?
Client sends chunked upload with progress events via WebSocket or polling. Server receives chunks, assembles. Use multipart/form-data with EnableBuffering disabled for streaming.
Architect 199. What is the role of a service mesh (e.g., Istio) in API architecture?
Manages service‑to‑service communication (routing, retries, circuit breaking, observability) transparently via sidecar proxies. Reduces code complexity.
Architect 200. How to implement API monetization (metering, billing)?
Track API usage per client (via API key). Integrate with a billing system. Enforce quotas. Use Azure API Management for built‑in monetization.
💼 Business Problem Scenarios (15)
[JsonIgnore] or conditional serialization.HttpClient or WCF client.🧪 Hands‑on Labs (10)
Lab 1: Build a CRUD REST API with ASP.NET Core and EF Core.
Create a Web API project, define model, DbContext, controller with GET, POST, PUT, DELETE, return appropriate status codes.
Lab 2: Implement JWT authentication and role‑based authorization.
Add JWT Bearer authentication, create token endpoint, protect controllers with [Authorize(Roles = "Admin")].
Lab 3: Create a GraphQL API with Hot Chocolate (Query + Mutation).
Define types, add query for products, mutation to add product. Test with Banana Cake Pop.
Lab 4: Add Swagger/OpenAPI documentation with custom examples.
Install Swashbuckle, configure IDocumentFilter and ISchemaFilter. Add XML comments.
Lab 5: Implement rate limiting with ASP.NET Core built‑in middleware.
Add RateLimiter service, configure fixed window policy, apply to endpoint. Test with load.
Lab 6: Build a real‑time notification system using SignalR.
Add SignalR hub, connect from client, push notifications from backend when events occur.
Lab 7: 🤖 AI Create an API endpoint that uses Azure Cognitive Services for text sentiment analysis.
Call Text Analytics API, send text, return sentiment score and category.
Lab 8: Implement a distributed cache with Redis for API responses.
Use IDistributedCache, store/retrieve serialized data, invalidate on update.
Lab 9: Write integration tests using WebApplicationFactory with in‑memory database.
Setup TestServer, replace DbContext with in‑memory, test endpoints.
Lab 10: Deploy an API to Azure App Service and configure CI/CD with GitHub Actions.
Create workflow YAML, build, publish, deploy to Azure Web App.
📝 Code‑Based Challenges (12)
Challenge 1: Refactor a controller that directly uses HttpClient to use IHttpClientFactory.
// Before: var client = new HttpClient();
// After: inject IHttpClientFactory, client = _httpClientFactory.CreateClient("myclient");Challenge 2: Write a middleware that logs request and response body (with buffering).
app.Use(async (context, next) => {
context.Request.EnableBuffering();
var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
context.Request.Body.Position = 0;
await next();
});Challenge 3: Implement a custom IAuthorizationRequirement that checks user's age.
public class MinimumAgeRequirement : IAuthorizationRequirement { public int Age { get; } }
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement> { ... }Challenge 4: Create an action filter that adds a custom header to all responses.
public class CustomHeaderFilter : IActionFilter {
public void OnActionExecuted(ActionExecutedContext context) {
context.HttpContext.Response.Headers.Add("X-Custom", "value");
}
}Challenge 5: Write a GraphQL resolver that uses DataLoader to batch load authors.
public async Task<Author> GetAuthorAsync([Parent] Book book, AuthorBatchDataLoader loader) => await loader.LoadAsync(book.AuthorId);Challenge 6: Implement a background service that reads from a channel and bulk inserts into DB.
public class BulkInserter : BackgroundService {
private readonly Channel<LogEntry> _channel;
protected override async Task ExecuteAsync(CancellationToken ct) { ... }
}Challenge 7: 🤖 AI Call OpenAI API to summarize text, with error handling and retry.
var retryPolicy = Policy.Handle<HttpRequestException>().RetryAsync(3);
await retryPolicy.ExecuteAsync(() => client.PostAsync(...));Challenge 8: Create a minimal API endpoint that accepts a file upload and returns a download URL.
app.MapPost("/upload", async (IFormFile file) => {
var path = Guid.NewGuid() + Path.GetExtension(file.FileName);
using var stream = File.Create(Path.Combine("uploads", path));
await file.CopyToAsync(stream);
return Results.Ok(new { url = $"/download/{path}" });
});Challenge 9: Build a custom JsonConverter to serialize enum as string with description.
public class EnumDescriptionConverter<T> : JsonConverter<T> where T : Enum { ... }Challenge 10: Write a middleware that blocks requests from specific IP addresses (blacklist).
if (blacklist.Contains(context.Connection.RemoteIpAddress)) {
context.Response.StatusCode = 403; return;
}Challenge 11: Implement a GraphQL @cost directive to limit field usage.
Create a custom schema directive and add cost metadata. During validation, sum costs and reject if too high.
Challenge 12: Convert a synchronous action to async using async/await and proper cancellation.
public async Task<ActionResult> GetAsync(CancellationToken ct) {
var data = await _service.GetDataAsync(ct);
return Ok(data);
}

No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam