If you’re preparing for a .NET Core Web API interview, it’s essential to understand the types of questions that may come your way. Scenario-based interview questions help interviewers gauge not only your technical knowledge but also your problem-solving and real-world application skills. In this blog, we’ll explore 20 scenario-based .NET Core Web API interview questions, providing you with insights to ace your interview.
1. How would you handle versioning in a .NET Core Web API?
Answer: API versioning is essential to ensure backward compatibility while allowing new features in the API. You can handle versioning in .NET Core Web API in several ways:
- URL Path Versioning (
/api/v1/products
) - Query String Versioning (
/api/products?version=1
) - Header Versioning (using custom headers like
api-version
)
2. What is the role of middleware in a .NET Core Web API? Can you give an example?
Answer: Middleware is used to handle requests and responses in the pipeline. You can add middleware to perform tasks such as logging, authentication, or exception handling. For example, adding a logging middleware to capture request details:
app.UseMiddleware<RequestLoggingMiddleware>();
3. How would you secure a Web API in .NET Core?
Answer: To secure a .NET Core Web API, use the following strategies:
- JWT Authentication: Implementing token-based authentication with JWT.
- OAuth 2.0: Using OAuth for securing resources.
- HTTPS: Enforcing SSL to ensure encrypted communication.
- Authorization: Using roles and claims to restrict access to endpoints.
4. How would you implement a rate-limiting feature in a .NET Core Web API?
Answer: Rate limiting can be implemented using custom middleware or libraries like AspNetCoreRateLimit
. You can define request limits for each user and apply rules based on client IP or API key.
5. How would you implement a logging mechanism in your .NET Core Web API?
Answer: .NET Core provides built-in logging with ILogger
. You can inject ILogger
into your controllers or services to log information, warnings, or errors:
private readonly ILogger<ProductController> _logger;
public ProductController(ILogger<ProductController> logger)
{
_logger = logger;
}
_logger.LogInformation("Fetching product list.");
6. How would you handle exceptions globally in .NET Core Web API?
Answer: Use exception middleware to catch all unhandled exceptions. You can implement this by adding custom middleware:
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
In the middleware, catch exceptions and return a proper HTTP response with an error message.
7. What are the differences between synchronous and asynchronous actions in a Web API?
Answer: Asynchronous actions use async
and await
to improve the scalability of an application, allowing it to handle more concurrent requests without blocking the thread. Synchronous actions block the request until the operation completes, which can affect performance in high-load scenarios.
8. How would you design a paginated API response in .NET Core?
Answer: For pagination, you can implement query parameters like page
and pageSize
. In your controller action, query the database with the page and pageSize values and return a paginated result:
var products = _context.Products
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
9. How would you ensure your Web API is scalable?
Answer: Scalability can be achieved by:
- Designing APIs with statelessness (avoid server-side session state).
- Using caching mechanisms like Redis.
- Implementing async operations for non-blocking calls.
- Load balancing across multiple server instances.
10. How would you handle file uploads in a .NET Core Web API?
Answer: To handle file uploads, use the IFormFile
interface in your controller:
[HttpPost("upload")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
var filePath = Path.Combine(_env.ContentRootPath, "uploads", file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok(new { filePath });
}
11. How do you implement caching in .NET Core Web API?
Answer: Caching can be implemented using the built-in IMemoryCache
or IDistributedCache
. For example:
var cacheKey = "products";
var products = _memoryCache.Get<List<Product>>(cacheKey);
if (products == null)
{
products = _context.Products.ToList();
_memoryCache.Set(cacheKey, products, TimeSpan.FromMinutes(5));
}
return Ok(products);
12. How would you handle cross-origin resource sharing (CORS) in a .NET Core Web API?
Answer: Use the AddCors
method to allow cross-origin requests in your Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowSpecificOrigin");
}
13. What are the advantages of using dependency injection in .NET Core Web API?
Answer: Dependency Injection (DI) promotes loose coupling and easier unit testing. It allows services to be injected into controllers and other classes, making your code more maintainable and testable. In .NET Core, DI is built into the framework, and you can register services in Startup.cs
.
14. How would you handle a 404 error in your Web API?
Answer: You can use the built-in NotFound()
method in your controller action:
if (product == null)
{
return NotFound(new { message = "Product not found." });
}
15. How would you manage environment-specific settings in a .NET Core Web API?
Answer: Use the appsettings.{Environment}.json
files for environment-specific configurations and access them via the IConfiguration
interface. For example, appsettings.Development.json
for development and appsettings.Production.json
for production settings.
16. How would you handle authorization in .NET Core Web API?
Answer: You can use roles and policies to implement authorization. For example, to allow only admin users:
[Authorize(Roles = "Admin")]
public IActionResult GetAdminData()
{
return Ok("Admin data");
}
17. How would you implement API documentation using Swagger in .NET Core Web API?
Answer: Install the Swashbuckle.AspNetCore
NuGet package and add the following to Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
});
}
18. How would you test a .NET Core Web API?
Answer: You can test your API using tools like Postman or implement unit tests using frameworks like xUnit
and Moq
. Integration tests can be done using TestServer
to simulate API calls.
19. How would you manage multiple databases in a .NET Core Web API?
Answer: You can configure multiple DbContext
classes in the Startup.cs
by registering each context in the dependency injection container:
services.AddDbContext<PrimaryDbContext>(options => options.UseSqlServer(connectionString1));
services.AddDbContext<SecondaryDbContext>(options => options.UseSqlServer(connectionString2));
20. How would you ensure your .NET Core Web API is optimized for performance?
Answer: Performance optimization can be achieved by:
- Using async operations for non-blocking I/O.
- Enabling caching for frequently accessed data.
- Applying pagination for large datasets.
- Optimizing database queries by using indexes and avoiding N+1 query problems.
FAQ Section
1. What is the difference between .NET Core and ASP.NET Core Web API?
Answer: .NET Core is the framework for building cross-platform applications, while ASP.NET Core is a web framework built on top of .NET Core that allows you to build web applications, including Web APIs.
2. How do you handle database transactions in a .NET Core Web API?
Answer: You can use the IDbContextTransaction
interface for managing transactions, ensuring that a set of operations is atomic.
3. How can I debug a .NET Core Web API?
Answer: You can use Visual Studio or Visual Studio Code to set breakpoints and use the debugger. You can also enable detailed error messages in development by setting app.UseDeveloperExceptionPage()
.