0% found this document useful (0 votes)
5 views

Asp.NET core web APi interview Question and ans

This document provides a comprehensive list of ASP.NET Core Web API interview questions and answers for experienced developers, covering basic, intermediate, and advanced topics. Key concepts include Middleware, Dependency Injection, JWT Authentication, CORS, and API Versioning, along with practical examples. The document also highlights the features of ASP.NET Core 6, such as minimal APIs and simplified configurations.

Uploaded by

sarfarajkhan254
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Asp.NET core web APi interview Question and ans

This document provides a comprehensive list of ASP.NET Core Web API interview questions and answers for experienced developers, covering basic, intermediate, and advanced topics. Key concepts include Middleware, Dependency Injection, JWT Authentication, CORS, and API Versioning, along with practical examples. The document also highlights the features of ASP.NET Core 6, such as minimal APIs and simplified configurations.

Uploaded by

sarfarajkhan254
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Here is a comprehensive list of ASP.

NET Core Web API interview questions and


answers tailored for experienced developers. These cover essential concepts,
practical scenarios, and advanced topics.

Basic Questions

1. What is ASP.NET Core Web API?


Answer:
ASP.NET Core Web API is a framework for building HTTP-based services
that can be accessed from various clients, including browsers, mobile
apps, and desktop applications. It is lightweight, modular, and built on
the .NET Core runtime.
2. What is the difference between ASP.NET Web API and ASP.NET Core
Web API?
Answer:
o ASP.NET Web API is part of the .NET Framework, while ASP.NET
Core Web API is cross-platform and runs on .NET Core.
o ASP.NET Core Web API provides a unified programming model for
MVC and API.
o Dependency injection is built-in in ASP.NET Core Web API.
3. What are the key features of ASP.NET Core Web API?
Answer:
o Cross-platform support
o Dependency Injection (DI)
o Middleware pipeline
o Built-in routing
o Support for modern front-end frameworks (Angular, React)
o Enhanced performance and lightweight

Intermediate Questions

4. Explain Middleware in ASP.NET Core.


Answer:
Middleware is software that handles requests and responses in the
application pipeline. It can process requests before passing them to the
next middleware or terminate the pipeline.
5. How does routing work in ASP.NET Core Web API?
Answer:
Routing is configured in the Startup.cs file or the Program.cs file in .NET
6+. Attribute routing and conventional routing are supported. Routes
map incoming requests to controller actions.
6. What is Dependency Injection (DI)? How is it implemented in ASP.NET
Core?
Answer:
DI is a design pattern used to achieve Inversion of Control (IoC). In
ASP.NET Core, services are registered in the IServiceCollection in the
Startup.cs file or Program.cs, and dependencies are injected into
controllers or other services via constructors.

Example:

public void ConfigureServices(IServiceCollection services)


{
services.AddTransient<IMyService, MyService>();
}

7. What is Model Binding in Web API?


Answer:
Model binding maps incoming HTTP request data to controller action
parameters. ASP.NET Core automatically binds data from sources like
the query string, route data, and request body.
8. How do you handle exceptions in ASP.NET Core Web API?
Answer:
o Use try-catch blocks in controllers or services.
o Implement global exception handling using middleware.
o Use UseExceptionHandler or DeveloperExceptionPage in the
middleware pipeline.

Example:

app.UseExceptionHandler("/Home/Error");

9. What is the difference between IActionResult and ActionResult<T>?


Answer:
o IActionResult: A non-generic interface for returning results.
o ActionResult<T>: Combines IActionResult and T (strongly-typed)
for better type safety.
Advanced Questions

10.What is the purpose of HttpContext in ASP.NET Core?


Answer:
HttpContext provides information about the HTTP request and response,
including user details, cookies, session, and request headers.
11.How do you secure an ASP.NET Core Web API?
Answer:
o Use HTTPS.
o Implement authentication and authorization (e.g., JWT, OAuth
2.0).
o Use anti-forgery tokens.
o Validate user inputs and sanitize data.
o Use CORS to control access.
12.What is CORS, and why is it important?
Answer:
CORS (Cross-Origin Resource Sharing) is a security feature that allows or
restricts resources on a web page to be requested from another domain.
It is crucial for enabling API access from different origins.
13.What are filters in ASP.NET Core?
Answer:
Filters are attributes used to execute custom logic before or after an
action method is invoked. Common filters include:
o Authorization Filter
o Resource Filter
o Action Filter
o Exception Filter
o Result Filter
14.How do you version APIs in ASP.NET Core?
Answer:
o URL versioning: /api/v1/resource
o Query string versioning: /api/resource?version=1.0
o Header versioning: api-version: 1.0
Use the Microsoft.AspNetCore.Mvc.Versioning package for API
versioning.
15.Explain the Repository Pattern in ASP.NET Core.
Answer:
The Repository Pattern abstracts the data access layer, providing a
central place to perform CRUD operations. It separates business logic
from data access logic, enhancing maintainability.
Scenario-Based Questions

16.How would you implement JWT-based authentication in an ASP.NET


Core Web API?
Answer:
o Install Microsoft.AspNetCore.Authentication.JwtBearer.
o Configure JWT in Program.cs:
o services.AddAuthentication(JwtBearerDefaults.AuthenticationSch
eme)
o .AddJwtBearer(options =>
o {
o options.TokenValidationParameters = new
TokenValidationParameters
o {
o ValidateIssuer = true,
o ValidateAudience = true,
o ValidateLifetime = true,
o ValidateIssuerSigningKey = true,
o ValidIssuer = "yourdomain.com",
o ValidAudience = "yourdomain.com",
o IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key
"))
o };
o });
17.How would you implement pagination in a Web API?
Answer:
Pass query parameters like pageNumber and pageSize. Use LINQ to skip
and take records:
18.var pagedData = data.Skip((pageNumber - 1) * pageSize).Take(pageSize);
19.What is the difference between AddScoped, AddSingleton, and
AddTransient?
Answer:
o AddScoped: One instance per request.
o AddSingleton: Single instance for the entire application lifetime.
o AddTransient: New instance every time it is requested.
20.How do you test an ASP.NET Core Web API?
Answer:
o Use integration testing with TestServer.
o Mock dependencies using frameworks like Moq.
o Write unit tests for services and controllers.
21.How do you log in ASP.NET Core?
Answer:
Use the built-in ILogger interface. Configure logging in Program.cs or
appsettings.json.
Example:
22.public class HomeController
23.{
24. private readonly ILogger<HomeController> _logger;
25. public HomeController(ILogger<HomeController> logger)
26. {
27. _logger = logger;
28. }
29.
30. public IActionResult Index()
31. {
32. _logger.LogInformation("Index method called.");
33. return View();
34. }
35.}

If you'd like to explore specific topics or questions further, let me know!

Here’s a comprehensive list of ASP.NET Core Web API interview Q&A with examples to
provide clarity:

1. What is ASP.NET Core Web API?

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:

public class RequestLoggingMiddleware


{
private readonly RequestDelegate _next;

public RequestLoggingMiddleware(RequestDelegate next)


{
_next = next;
}

public async Task Invoke(HttpContext context)


{
Console.WriteLine($"Request: {context.Request.Method}
{context.Request.Path}");
await _next(context);
}
}

// 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}");
}
}

Request: GET /api/products/1


Response: Product 1

4. How do you handle exceptions in ASP.NET Core Web API?

Answer:
Use try-catch, global exception handling, or middleware for handling
exceptions.

Example:
Global Exception Middleware:

public class ExceptionHandlingMiddleware


{
private readonly RequestDelegate _next;

public ExceptionHandlingMiddleware(RequestDelegate next)


{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync($"An error occurred:
{ex.Message}");
}
}
}

// In Program.cs
app.UseMiddleware<ExceptionHandlingMiddleware>();

5. How do you implement Dependency Injection?

Answer:
Services are registered in the DI container and injected into controllers or
classes.

Example:
Service Interface and Implementation:

public interface IProductService


{
IEnumerable<string> GetProducts();
}

public class ProductService : IProductService


{
public IEnumerable<string> GetProducts()
{
return new List<string> { "Product1", "Product2" };
}
}
// Registering in Program.cs
services.AddScoped<IProductService, ProductService>();

// Using in Controller
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;

public ProductsController(IProductService productService)


{
_productService = productService;
}

[HttpGet]
public IActionResult GetProducts()
{
var products = _productService.GetProducts();
return Ok(products);
}
}

6. How do you implement JWT Authentication?

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"))
};
});

Generate JWT Token:

public string GenerateToken(string username)


{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes("your_secret_key");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name,
username) }),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new
SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}

7. How do you implement API Versioning?

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");
}

8. How do you implement pagination in an API?

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);
}

Request: GET /api/products?pageNumber=2&pageSize=5


Response: Product 6 to Product 10

9. How do you secure an API with HTTPS and CORS?


Answer:

 HTTPS: Use app.UseHttpsRedirection().


 CORS: Configure policies to restrict origins.

Example:

services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});

// In Program.cs
app.UseCors("AllowSpecificOrigin");
app.UseHttpsRedirection();

10. What is the Repository Pattern?

Answer:
The Repository Pattern abstracts data access logic into a separate repository
class.

Example:

public interface IProductRepository


{
IEnumerable<string> GetProducts();
}

public class ProductRepository : IProductRepository


{
public IEnumerable<string> GetProducts()
{
return new List<string> { "Product1", "Product2" };
}
}
// Using the repository
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _repository;

public ProductsController(IProductRepository repository)


{
_repository = repository;
}

[HttpGet]
public IActionResult GetProducts()
{
var products = _repository.GetProducts();
return Ok(products);
}
}

These examples cover common real-world scenarios and provide practical


insights into how to implement them effectively. Let me know if you'd like to
dive deeper into any specific topic!

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.

1. What is ASP.NET Core 6 Web API?

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.

Example (Minimal API):


var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/api/products", () => new[] { "Product1", "Product2",


"Product3" });

app.Run();

2. What are Minimal APIs?

Answer:
Minimal APIs simplify the creation of APIs by reducing the boilerplate code
required for controllers and configurations.

Example:

var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();

app.MapGet("/api/hello", () => "Hello, World!");

app.Run();

3. How do you configure Dependency Injection in ASP.NET Core 6?

Answer:
Register services in the DI container using builder.Services.

Example:

builder.Services.AddScoped<IProductService, ProductService>();

var app = builder.Build();

app.MapGet("/api/products", (IProductService service) =>


service.GetProducts());

app.Run();

public interface IProductService


{
IEnumerable<string> GetProducts();
}

public class ProductService : IProductService


{
public IEnumerable<string> GetProducts() => new List<string> { "Product1",
"Product2" };
}

4. How do you implement Global Exception Handling in ASP.NET Core 6?

Answer:
Use UseExceptionHandler or custom middleware.

Example:

var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();

app.UseExceptionHandler("/error");

app.MapGet("/", () => throw new Exception("Something went wrong!"));


app.MapGet("/error", () => Results.Problem("An error occurred."));

app.Run();

5. How do you implement JWT Authentication in ASP.NET Core 6?

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"))
};
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/secure", [Authorize] () => "This is a secure endpoint");

app.Run();

6. How do you implement Routing in ASP.NET Core 6?

Answer:
Routes can be defined using MapGet, MapPost, etc., in minimal APIs.

Example:

var app = builder.Build();

app.MapGet("/api/products/{id}", (int id) => $"Product ID: {id}");

app.Run();

7. How do you enable CORS in ASP.NET Core 6?

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());
});

var app = builder.Build();

app.UseCors("AllowSpecificOrigin");

app.MapGet("/api/products", () => new[] { "Product1", "Product2" });

app.Run();

8. How do you implement Versioning in ASP.NET Core 6?

Answer:
Add API versioning services and use version-specific routes.

Example:

builder.Services.AddApiVersioning();

var app = builder.Build();

app.MapGet("/api/v1/products", () => "Version 1: Products");


app.MapGet("/api/v2/products", () => "Version 2: Products");

app.Run();

9. How do you implement Pagination in ASP.NET Core 6?

Answer:
Use Skip and Take LINQ methods for pagination.

Example:

var app = builder.Build();


app.MapGet("/api/products", (int page = 1, int size = 10) =>
{
var products = Enumerable.Range(1, 100).Select(x => $"Product {x}");
var paginated = products.Skip((page - 1) * size).Take(size);
return paginated;
});

app.Run();

10. How do you test Web APIs in ASP.NET Core 6?

Answer:
Test APIs using tools like Postman or automated testing frameworks.

Example (xUnit):

public class ProductsApiTests


{
[Fact]
public async Task GetProducts_ShouldReturnOk()
{
var app = new WebApplicationFactory<Program>();
var client = app.CreateClient();

var response = await client.GetAsync("/api/products");

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}

11. How do you use Entity Framework Core in ASP.NET Core 6?

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.MapGet("/api/products", (AppDbContext context) =>


context.Products.ToList());

app.Run();

public class AppDbContext : DbContext


{
public DbSet<Product> Products { get; set; }
}

public class Product


{
public int Id { get; set; }
public string Name { get; set; }
}

12. How do you use Filters in ASP.NET Core 6?

Answer:
Filters modify request/response processing.

Example (Global Filter):

builder.Services.AddControllers(options =>
{
options.Filters.Add(new AuthorizeFilter());
});

var app = builder.Build();

app.MapControllers();

app.Run();

13. How do you implement Health Checks in ASP.NET Core 6?

Answer:
Add health check services and map endpoints.
Example:

builder.Services.AddHealthChecks();

var app = builder.Build();

app.MapHealthChecks("/health");

app.Run();

14. How do you configure Logging in ASP.NET Core 6?

Answer:
Use ILogger for structured logging.

Example:

var builder = WebApplication.CreateBuilder(args);


var logger =
builder.Services.BuildServiceProvider().GetRequiredService<ILogger<Program>
>();

logger.LogInformation("Application is starting...");

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

15. How do you create a Custom Middleware in ASP.NET Core 6?

Answer:
Create a middleware class and use it in the pipeline.

Example:

var app = builder.Build();

app.Use(async (context, next) =>


{
Console.WriteLine($"Request: {context.Request.Path}");
await next();
Console.WriteLine($"Response: {context.Response.StatusCode}");
});

app.MapGet("/", () => "Hello Middleware!");

app.Run();

These examples focus on ASP.NET Core 6 features such as minimal APIs,


simplified dependency injection, and modern routing. Let me know if you'd like
to explore a specific topic further!

You might also like