Asp.NET core web APi interview Question and ans
Asp.NET core web APi interview Question and ans
Basic Questions
Intermediate Questions
Example:
Example:
app.UseExceptionHandler("/Home/Error");
Here’s a comprehensive list of ASP.NET Core Web API interview Q&A with examples to
provide clarity:
Answer:
ASP.NET Core Web API is a framework for building HTTP-based services that
can be accessed from various clients (browsers, mobile apps, IoT devices).
Example:
Create a simple Web API in ASP.NET Core:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new List<string> { "Product1", "Product2", "Product3" };
return Ok(products);
}
}
2. What is Middleware?
Answer:
Middleware is software that processes requests and responses in the HTTP
pipeline.
Example:
Custom Middleware to log requests:
// In Program.cs
app.UseMiddleware<RequestLoggingMiddleware>();
3. How does routing work in ASP.NET Core?
Answer:
Routing maps incoming requests to actions in controllers.
Example:
Attribute Routing:
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
return Ok($"Product {id}");
}
}
Answer:
Use try-catch, global exception handling, or middleware for handling
exceptions.
Example:
Global Exception Middleware:
// In Program.cs
app.UseMiddleware<ExceptionHandlingMiddleware>();
Answer:
Services are registered in the DI container and injected into controllers or
classes.
Example:
Service Interface and Implementation:
// Using in Controller
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
[HttpGet]
public IActionResult GetProducts()
{
var products = _productService.GetProducts();
return Ok(products);
}
}
Answer:
Configure JWT authentication to secure the API.
Example:
Configure JWT in Program.cs:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
Answer:
Install the Microsoft.AspNetCore.Mvc.Versioning package.
Example:
Configure versioning in Program.cs:
services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
Define versions in controllers:
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV1Controller : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Version 1");
}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV2Controller : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Version 2");
}
Answer:
Use Skip and Take to fetch paginated results.
Example:
[HttpGet]
public IActionResult GetProducts(int pageNumber = 1, int pageSize = 10)
{
var products = Enumerable.Range(1, 100).Select(x => $"Product {x}");
var pagedData = products.Skip((pageNumber - 1) * pageSize).Take(pageSize);
return Ok(pagedData);
}
Example:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// In Program.cs
app.UseCors("AllowSpecificOrigin");
app.UseHttpsRedirection();
Answer:
The Repository Pattern abstracts data access logic into a separate repository
class.
Example:
[HttpGet]
public IActionResult GetProducts()
{
var products = _repository.GetProducts();
return Ok(products);
}
}
Here’s the updated set of ASP.NET Core 6 Web API interview questions and answers with
examples, tailored for the ASP.NET Core 6 framework, which incorporates many modern
practices like minimal APIs, top-level statements, and simplified configurations.
Answer:
ASP.NET Core 6 Web API is a lightweight, cross-platform framework for
building HTTP services, optimized with features like minimal APIs and
improved performance.
app.Run();
Answer:
Minimal APIs simplify the creation of APIs by reducing the boilerplate code
required for controllers and configurations.
Example:
app.Run();
Answer:
Register services in the DI container using builder.Services.
Example:
builder.Services.AddScoped<IProductService, ProductService>();
app.Run();
Answer:
Use UseExceptionHandler or custom middleware.
Example:
app.UseExceptionHandler("/error");
app.Run();
Answer:
Configure JWT in builder.Services and apply authentication middleware.
Example:
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
app.UseAuthentication();
app.UseAuthorization();
app.Run();
Answer:
Routes can be defined using MapGet, MapPost, etc., in minimal APIs.
Example:
app.Run();
Answer:
Configure CORS policies in builder.Services and use them in the app.
Example:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
policy.WithOrigins("https://example.com").AllowAnyMethod().AllowAnyHeade
r());
});
app.UseCors("AllowSpecificOrigin");
app.Run();
Answer:
Add API versioning services and use version-specific routes.
Example:
builder.Services.AddApiVersioning();
app.Run();
Answer:
Use Skip and Take LINQ methods for pagination.
Example:
app.Run();
Answer:
Test APIs using tools like Postman or automated testing frameworks.
Example (xUnit):
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
Answer:
Register the DbContext in builder.Services and use it in endpoints.
Example:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer("YourConnectionString"));
var app = builder.Build();
app.Run();
Answer:
Filters modify request/response processing.
builder.Services.AddControllers(options =>
{
options.Filters.Add(new AuthorizeFilter());
});
app.MapControllers();
app.Run();
Answer:
Add health check services and map endpoints.
Example:
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
app.Run();
Answer:
Use ILogger for structured logging.
Example:
logger.LogInformation("Application is starting...");
app.Run();
Answer:
Create a middleware class and use it in the pipeline.
Example:
app.Run();