0% found this document useful (0 votes)
11 views6 pages

Advanced .NET Core Web API Interview Q&A

The document provides advanced interview questions and answers related to .NET Core 6 to 8 Web API, covering key topics such as middleware, dependency injection, JWT authentication, health checks, OpenAPI/Swagger, testing APIs, configuration binding, and clean architecture/CQRS. It includes explanations of concepts, code snippets for implementation, and best practices. This resource is aimed at helping developers prepare for technical interviews in the .NET Core ecosystem.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Advanced .NET Core Web API Interview Q&A

The document provides advanced interview questions and answers related to .NET Core 6 to 8 Web API, covering key topics such as middleware, dependency injection, JWT authentication, health checks, OpenAPI/Swagger, testing APIs, configuration binding, and clean architecture/CQRS. It includes explanations of concepts, code snippets for implementation, and best practices. This resource is aimed at helping developers prepare for technical interviews in the .NET Core ecosystem.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

.

NET Core 6 to 8 Web API - Advanced Interview Questions and Answers

1. Middleware Pipeline

Q1. What is the purpose of middleware in [Link] Core? A1. Middleware is software that is
assembled into an application pipeline to handle requests and responses. Each component:

• Can perform operations before and after the next delegate.


• Has access to HttpContext.
• Can short-circuit the pipeline.

Q2. How do you create custom middleware in [Link] Core? A2.

public class LoggingMiddleware


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

public async Task Invoke(HttpContext context)


{
[Link]($"Request: {[Link]}");
await _next(context);
[Link]($"Response: {[Link]}");
}
}

Add in pipeline:

[Link]<LoggingMiddleware>();

Q3. What is the order of middleware execution and why is it important? A3. Middleware runs in the
order it is added in [Link]. Order is critical because:

• UseAuthentication() must come before UseAuthorization().


• Error handling middleware should be first.

2. Dependency Injection (DI)

Q1. What is the difference between Transient, Scoped, and Singleton lifetimes in DI? A1.

• Transient: New instance every time.


• Scoped: One instance per HTTP request.
• Singleton: One instance for entire application lifetime.

Q2. When should you use Scoped services? A2. Scoped services are ideal for repository or
business layer services that work with DbContext per request. Using singleton for such services
may result in data corruption or unexpected behavior.

Q3. How do you inject services into middleware? A3. Inject via Invoke method:

public async Task Invoke(HttpContext context, IMyService service)

Or use factory pattern with [Link].

3. JWT Authentication

Q1. What are the main components of JWT token authentication? A1.

• Header: Contains type and algorithm.


• Payload: Claims (user data).
• Signature: To verify token integrity.

Q2. How do you generate a JWT token? A2.

var tokenHandler = new JwtSecurityTokenHandler();


var key = [Link](secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim([Link], [Link]
name) }),
Expires = [Link](1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key)
, SecurityAlgorithms.HmacSha256Signature)
};
var token = [Link](tokenDescriptor);
return [Link](token);

Q3. How do you validate a JWT token? A3. Configure in [Link]:

[Link]([Link])
.AddJwtBearer(options =>
{
[Link] = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});

4. Health Checks

Q1. What are Health Checks in [Link] Core? A1. Health Checks provide a way to expose
application health status via HTTP endpoints. Useful in container orchestration (Kubernetes,
Docker).

Q2. How to implement a basic health check? A2.

[Link]();
[Link]("/health");

Q3. How to add custom health checks? A3.

[Link]()
.AddCheck<MyCustomHealthCheck>("MyHealth");

Implement IHealthCheck:

public class MyCustomHealthCheck : IHealthCheck


{
public Task<HealthCheckResult> CheckHealthAsync(...)
{
return [Link]([Link]("Service is OK"));
}
}

5. OpenAPI / Swagger

Q1. How do you enable Swagger in .NET Core? A1.

[Link]();
[Link]();
[Link]();
[Link]();

Q2. How do you secure Swagger with JWT? A2. Use AddSecurityDefinition and
AddSecurityRequirement:
[Link]("Bearer", new OpenApiSecurityScheme
{
In = [Link],
Description = "Please enter token",
Name = "Authorization",
Type = [Link],
BearerFormat = "JWT",
Scheme = "bearer"
});

Q3. How to customize Swagger UI? A3. You can set custom title, route, expand doc:

[Link](c => {
[Link]("/swagger/v1/[Link]", "My API V1");
[Link] = "docs";
});

6. Testing APIs (xUnit, Moq)

Q1. How to test controllers using xUnit and Moq? A1.

• Use Moq to mock dependencies.


• Inject into controller.
• Use Assert to validate result.

Q2. What is WebApplicationFactory? A2. Helps to test entire app pipeline including middleware.
Use with TestServer.

var factory = new WebApplicationFactory<Startup>();


var client = [Link]();

Q3. How do you test HTTP endpoints? A3.

var response = await [Link]("/api/products");


[Link]([Link], [Link]);

7. Configuration Binding

Q1. How do you bind [Link] to POCO? A1.

public class AppSettings


{
public string AppName { get; set; }
}
[Link]<AppSettings>([Link]("AppSettings"));

Q2. How to access configuration in a controller or service? A2.

public class MyService


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

Q3. How to reload configuration at runtime? A3. Use IOptionsSnapshot<T> for scoped services
or IOptionsMonitor<T> for singleton.

8. Clean Architecture / CQRS

Q1. What is Clean Architecture? A1. It separates concerns into layers:

• Presentation
• Application
• Domain
• Infrastructure This improves testability and scalability.

Q2. What is CQRS? A2. Command Query Responsibility Segregation:

• Commands modify state.


• Queries fetch data.
• Helps in scaling read and write operations independently.

Q3. What is MediatR and how does it fit in CQRS? A3. MediatR implements the mediator pattern. It
decouples senders and handlers of commands/queries.

public record GetProductByIdQuery(int Id) : IRequest<Product>;

Handler:

public class GetProductByIdHandler : IRequestHandler<GetProductByIdQuery, Pro


duct>

Send via:

var result = await _mediator.Send(new GetProductByIdQuery(id));


Request to Repost If this helped you, please like, comment, and repost to help fellow
developers. Let’s grow together!

You might also like