issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

Top 45 ASP.NET Core Interview Questions 2026

17 min read
Interview Questions
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~20 min

ASP.NET Core is Microsoft's high-performance, cross-platform web framework. Candidates report that middleware pipeline, dependency injection, Web API, Entity Framework Core, and JWT auth are the most frequently tested topics in .NET developer interviews.

Pair with Java Interview Questions 2026 for cross-language comparison. Confirm current interview requirements on the official careers portal of your target company.


Table of Contents

  1. ASP.NET Core Fundamentals (Q1-Q12)
  2. Web API and Controllers (Q13-Q22)
  3. Entity Framework Core (Q23-Q32)
  4. Authentication and Security (Q33-Q39)
  5. Advanced Topics (Q40-Q45)
  6. Mock Interview: 5 Questions
  7. FAQ

ASP.NET Core Fundamentals

Q1. What is ASP.NET Core and how does it differ from ASP.NET Framework? Easy

FeatureASP.NET CoreASP.NET Framework
PlatformCross-platform (Windows/Linux/macOS)Windows only
Runtime.NET Core / .NET 5+.NET Framework
PerformanceHigh (Kestrel web server)Lower
HostingSelf-hosting, Docker, IISIIS only
DIBuilt-inVia third-party
ConfigurationJSON, env vars, secretsweb.config XML

Q2. What is the request pipeline in ASP.NET Core? Medium

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

// Middleware order matters
app.UseExceptionHandler("/error");  // outermost: catches all exceptions
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();            // who are you?
app.UseAuthorization();             // what can you do?
app.UseRateLimiter();
app.MapControllers();               // endpoint routing

app.Run();

Candidates report that middleware ordering is a frequent interview question. Authentication must come before Authorization.


Q3. What is middleware? Medium

// Custom middleware
public class TimingMiddleware
{
    private readonly RequestDelegate _next;
    
    public TimingMiddleware(RequestDelegate next) => _next = next;
    
    public async Task InvokeAsync(HttpContext context)
    {
        var sw = Stopwatch.StartNew();
        await _next(context);  // call next middleware
        sw.Stop();
        context.Response.Headers["X-Elapsed-Ms"] = sw.ElapsedMilliseconds.ToString();
    }
}

// Register
app.UseMiddleware<TimingMiddleware>();

// Or use Run (terminal - no next)
app.Run(async context => await context.Response.WriteAsync("Hello"));

// Use (passes to next)
app.Use(async (context, next) => {
    Console.WriteLine("Before");
    await next(context);
    Console.WriteLine("After");
});

Q4. What is dependency injection in ASP.NET Core? Medium

// Register services
builder.Services.AddSingleton<IConfiguration>(config);
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddTransient<IEmailService, SmtpEmailService>();

// Service lifetimes
// Singleton: one instance for app lifetime
// Scoped: one instance per HTTP request
// Transient: new instance every time requested

// Inject
public class UserController : ControllerBase
{
    private readonly IUserRepository _users;
    private readonly IEmailService _email;
    
    public UserController(IUserRepository users, IEmailService email)
    {
        _users = users;
        _email = email;
    }
}

Q5. What is appsettings.json and configuration? Easy

// appsettings.json
{
    "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=MyApp;..."
    },
    "JWT": {
        "SecretKey": "your-secret-key",
        "Issuer": "myapp.com",
        "ExpiryMinutes": 60
    },
    "Features": {
        "EnableCaching": true
    }
}
// Access in code
var connStr = builder.Configuration.GetConnectionString("DefaultConnection");
var jwtKey = builder.Configuration["JWT:SecretKey"];

// Strongly-typed options
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection("JWT"));

// Inject
public class AuthService(IOptions<JwtOptions> jwtOptions)
{
    var key = jwtOptions.Value.SecretKey;
}

Q6. What is the difference between IOptions, IOptionsMonitor, and IOptionsSnapshot? Advanced

InterfaceScopeReloads at runtime
IOptions<T>SingletonNo
IOptionsSnapshot<T>Scoped (per request)Yes (for scoped)
IOptionsMonitor<T>SingletonYes (event notification)
// IOptionsMonitor: change notification callback
public class FeatureService(IOptionsMonitor<FeatureFlags> monitor)
{
    public FeatureService(IOptionsMonitor<FeatureFlags> monitor)
    {
        monitor.OnChange(flags => {
            Console.WriteLine($"Features changed: {flags.EnableCaching}");
        });
    }
}

Q7. What is IHostedService and BackgroundService? Advanced

public class EmailWorker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await ProcessEmailQueue();
            await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
        }
    }
}

builder.Services.AddHostedService<EmailWorker>();

Q8. What is minimal API? Medium

// .NET 6+ minimal API (no controllers)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDb>(opt => opt.UseInMemoryDatabase("AppDb"));

var app = builder.Build();

app.MapGet("/users", async (AppDb db) => await db.Users.ToListAsync());
app.MapGet("/users/{id}", async (int id, AppDb db) =>
    await db.Users.FindAsync(id) is User user ? Results.Ok(user) : Results.NotFound());
app.MapPost("/users", async (User user, AppDb db) => {
    db.Users.Add(user);
    await db.SaveChangesAsync();
    return Results.Created($"/users/{user.Id}", user);
});
app.MapDelete("/users/{id}", async (int id, AppDb db) => {
    if (await db.Users.FindAsync(id) is User user) {
        db.Users.Remove(user);
        await db.SaveChangesAsync();
        return Results.NoContent();
    }
    return Results.NotFound();
});
app.Run();

Q9. What is environment-specific configuration? Medium

// appsettings.json (base)
// appsettings.Development.json (overrides for Development)
// appsettings.Production.json

// Set via ASPNETCORE_ENVIRONMENT env var
// Development: auto-detects when running with dotnet run

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

Q10. What is ILogger and logging in ASP.NET Core? Medium

public class UserService
{
    private readonly ILogger<UserService> _logger;
    
    public UserService(ILogger<UserService> logger) => _logger = logger;
    
    public async Task<User> CreateUser(CreateUserRequest req)
    {
        _logger.LogInformation("Creating user {Email}", req.Email);
        
        try
        {
            var user = await _repo.Create(req);
            _logger.LogInformation("User created: {UserId}", user.Id);
            return user;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create user {Email}", req.Email);
            throw;
        }
    }
}
// Configure providers in appsettings.json:
// "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning" } }

Q11. Predict the output: middleware order. Medium

app.Use(async (ctx, next) => {
    Console.Write("A ");
    await next(ctx);
    Console.Write("a ");
});
app.Use(async (ctx, next) => {
    Console.Write("B ");
    await next(ctx);
    Console.Write("b ");
});
app.Run(ctx => { Console.Write("C "); return Task.CompletedTask; });

Output: A B C b a

Explanation: Middleware processes request inward (A -> B -> C), then response outward (b -> a).


Q12. What is CORS configuration? Medium

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
        policy.WithOrigins("https://myfrontend.com")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials());
    
    options.AddDefaultPolicy(policy =>
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});

app.UseCors("AllowFrontend");  // apply named policy

Web API and Controllers

Q13. What is a Controller in ASP.NET Core? Easy

[ApiController]
[Route("api/[controller]")]  // /api/users
public class UsersController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<IEnumerable<UserDto>>> GetAll()
    {
        var users = await _repo.GetAllAsync();
        return Ok(users);
    }
    
    [HttpGet("{id:int}")]
    public async Task<ActionResult<UserDto>> GetById(int id)
    {
        var user = await _repo.GetByIdAsync(id);
        return user is null ? NotFound() : Ok(user);
    }
    
    [HttpPost]
    public async Task<ActionResult<UserDto>> Create([FromBody] CreateUserRequest req)
    {
        var user = await _repo.CreateAsync(req);
        return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);
    }
    
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        await _repo.DeleteAsync(id);
        return NoContent();
    }
}

Q14. What are model binding sources? Medium

public ActionResult Create(
    [FromRoute] int id,           // from URL path
    [FromQuery] string search,    // ?search=...
    [FromBody] UserRequest body,  // from request body
    [FromHeader] string apiKey,   // from header
    [FromForm] IFormFile file,    // from multipart form
    [FromServices] ILogger logger // from DI container
)

[ApiController] enables automatic model binding inferences based on parameter type.


Q15. What is model validation? Medium

public class CreateUserRequest
{
    [Required]
    [StringLength(100, MinimumLength = 2)]
    public string Name { get; set; }
    
    [Required, EmailAddress]
    public string Email { get; set; }
    
    [Range(18, 120)]
    public int Age { get; set; }
    
    [RegularExpression(@"^\+91[0-9]{10}$")]
    public string? Phone { get; set; }
}

// [ApiController] automatically returns 400 on validation failure
// Manual check:
if (!ModelState.IsValid)
    return BadRequest(ModelState);

Q16. What is ActionResult<T> vs IActionResult? Medium

// IActionResult: non-generic, no return type info in Swagger
public IActionResult Get(int id) => Ok(new User());

// ActionResult<T>: type info exposed in OpenAPI
public ActionResult<User> Get(int id)
{
    var user = _repo.Get(id);
    if (user == null) return NotFound();  // IActionResult
    return user;  // implicit conversion to ActionResult<User>
}

Q17. What are filters? Advanced

Filter typeRuns whenExample use
AuthorizationBefore actionCheck permissions
ResourceAfter auth, before model bindingCaching
ActionAround action executionLogging
ExceptionWhen unhandled exceptionGlobal error formatting
ResultAround result executionResponse transformation
public class AuditFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext ctx)
    {
        _logger.LogInformation("Action {Action} starting", ctx.ActionDescriptor.DisplayName);
    }
    
    public void OnActionExecuted(ActionExecutedContext ctx)
    {
        _logger.LogInformation("Action {Action} completed", ctx.ActionDescriptor.DisplayName);
    }
}

// Register globally or per controller/action
builder.Services.AddControllers(opts => opts.Filters.Add<AuditFilter>());
[ServiceFilter(typeof(AuditFilter))]

Q18. What is ProblemDetails? Medium

// RFC 7807 standard error response format
return Problem(
    title: "Validation failed",
    detail: "Email must be unique",
    statusCode: 400,
    instance: HttpContext.Request.Path
);

// Or use ProblemDetails directly
return new BadRequestObjectResult(new ProblemDetails
{
    Title = "Bad Request",
    Detail = "Invalid input",
    Status = 400,
    Extensions = { ["errors"] = ModelState }
});

Q19. What are route constraints? Medium

[HttpGet("{id:int:min(1)}")]         // id must be int >= 1
[HttpGet("{name:alpha:minlength(3)}")]  // name alpha, length >= 3
[HttpGet("{date:datetime}")]          // parse as datetime
[HttpGet("{id:guid}")]               // GUID format
[HttpGet("{version:regex(v\\d+)}")]  // regex match

// Custom constraint
public class EvenNumberConstraint : IRouteConstraint
{
    public bool Match(HttpContext? ctx, IRouter? route, string key,
                      RouteValueDictionary values, RouteDirection dir)
    {
        return int.TryParse(values[key]?.ToString(), out int n) && n % 2 == 0;
    }
}

Q20. What is API versioning? Advanced

builder.Services.AddApiVersioning(opt => {
    opt.DefaultApiVersion = new ApiVersion(1, 0);
    opt.AssumeDefaultVersionWhenUnspecified = true;
    opt.ApiVersionReader = ApiVersionReader.Combine(
        new UrlSegmentApiVersionReader(),   // /api/v1/users
        new HeaderApiVersionReader("X-Version"),  // header
        new QueryStringApiVersionReader("version") // ?version=1.0
    );
});

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/users")]
public class UsersV1Controller : ControllerBase { }

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/users")]
public class UsersV2Controller : ControllerBase { }

Q21. What is the [ApiController] attribute? Easy

  1. Automatic model binding from [FromBody], [FromQuery], etc.
  2. Automatic 400 response on ModelState.IsValid == false
  3. Automatic ProblemDetails error response format
  4. Requires attribute routing (no conventional routes)

Q22. Predict the output: Medium

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return id > 0 ? $"Item {id}" : NotFound();
    }
}
// GET /api/test/5 -> ?
// GET /api/test/0 -> ?

Output:

  • GET /api/test/5 returns 200 OK with body "Item 5"
  • GET /api/test/0 returns 404 Not Found

Entity Framework Core

Q23. What is Entity Framework Core? Easy

public class User
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
    public ICollection<Order> Orders { get; set; } = [];
}

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
    public DbSet<User> Users { get; set; }
    public DbSet<Order> Orders { get; set; }
}

// Register
builder.Services.AddDbContext<AppDbContext>(opt =>
    opt.UseNpgsql(builder.Configuration.GetConnectionString("Default")));

Q24. What are EF Core migrations? Medium

dotnet ef migrations add InitialCreate     # generate migration
dotnet ef database update                  # apply to database
dotnet ef migrations remove                # remove last migration
dotnet ef database update 0                # revert all
dotnet ef migrations script               # generate SQL script

Q25. What is LINQ in EF Core? Medium

// Filtering
var adults = await context.Users
    .Where(u => u.Age >= 18 && u.Active)
    .ToListAsync();

// Select projection
var names = await context.Users
    .Select(u => new { u.Id, u.Name })
    .ToListAsync();

// Include (eager loading)
var usersWithOrders = await context.Users
    .Include(u => u.Orders)
    .ThenInclude(o => o.Items)
    .Where(u => u.Orders.Count > 0)
    .ToListAsync();

// Aggregates
var avgAge = await context.Users.AverageAsync(u => u.Age);
var count = await context.Users.CountAsync(u => u.Active);

Q26. What is the difference between Find, First, Single, and FirstOrDefault? Medium

await context.Users.FindAsync(id)          // by PK, checks cache first, null if not found
await context.Users.FirstAsync(u => ...)   // first matching, throws if none
await context.Users.FirstOrDefaultAsync()  // first or null
await context.Users.SingleAsync(u => ...)  // exactly one, throws if 0 or 2+
await context.Users.SingleOrDefaultAsync() // one or null, throws if 2+

Q27. What is change tracking in EF Core? Medium

// EF Core tracks entities loaded via context (similar to Hibernate)
var user = await context.Users.FindAsync(1);
user.Name = "New Name";  // change tracked
await context.SaveChangesAsync();  // generates UPDATE automatically

// Disable tracking for read-only queries (performance)
var users = await context.Users.AsNoTracking().ToListAsync();

// Check tracked state
var entry = context.Entry(user);
Console.WriteLine(entry.State);  // EntityState.Modified

Q28. What are raw SQL queries in EF Core? Advanced

// Mapped to entity
var users = await context.Users
    .FromSqlRaw("SELECT * FROM Users WHERE Score > {0}", 80)
    .ToListAsync();

// Interpolated (parameterized, safe from injection)
int minScore = 80;
var users2 = await context.Users
    .FromSqlInterpolated($"SELECT * FROM Users WHERE Score > {minScore}")
    .ToListAsync();

// Non-query raw SQL
await context.Database.ExecuteSqlRawAsync(
    "UPDATE Users SET Active = 0 WHERE LastLogin < {0}", cutoffDate);

Q29. What is bulk operations performance in EF Core? Advanced

// EF Core 7+: bulk operations without loading entities
await context.Users
    .Where(u => !u.Active)
    .ExecuteDeleteAsync();  // single DELETE SQL

await context.Users
    .Where(u => u.LastLogin < cutoff)
    .ExecuteUpdateAsync(s => s
        .SetProperty(u => u.Active, false)
        .SetProperty(u => u.UpdatedAt, DateTime.UtcNow));  // single UPDATE SQL

Q30. What is the ValueObject pattern with EF Core? Advanced

[Owned]  // maps as columns in owner's table
public record Address(string Street, string City, string Pincode);

public class User
{
    public int Id { get; set; }
    public Address HomeAddress { get; set; } = null!;
    // columns: HomeAddress_Street, HomeAddress_City, HomeAddress_Pincode
}

Q31. What are compiled queries? Advanced

private static readonly Func<AppDbContext, int, Task<User?>> GetUserById =
    EF.CompileAsyncQuery((AppDbContext ctx, int id) =>
        ctx.Users.FirstOrDefault(u => u.Id == id));

// Use (skips LINQ -> SQL translation on each call)
var user = await GetUserById(context, userId);

Q32. Predict the output: N+1 in EF Core. Advanced

var departments = await context.Departments.ToListAsync();
foreach (var dept in departments)
{
    var count = dept.Employees.Count;  // lazy loading not default in EF Core
}

Output: Throws InvalidOperationException or returns 0 because EF Core does NOT lazy load by default (unlike Hibernate). You must use .Include() for eager loading or enable lazy loading proxy explicitly.


Authentication and Security

Q33. How do you implement JWT authentication? Medium

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(config["JWT:Secret"])),
            ValidateIssuer = true,
            ValidIssuer = config["JWT:Issuer"],
            ValidateAudience = true,
            ValidAudience = config["JWT:Audience"],
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
    });

// Generate token
var token = new JwtSecurityToken(
    issuer: issuer,
    audience: audience,
    claims: claims,
    expires: DateTime.UtcNow.AddHours(1),
    signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);

Q34. What is [Authorize] and policy-based auth? Medium

[Authorize]                              // any authenticated user
[Authorize(Roles = "Admin")]             // specific role
[Authorize(Policy = "MinAge18")]         // custom policy

// Define policy
builder.Services.AddAuthorization(opts => {
    opts.AddPolicy("MinAge18", policy =>
        policy.RequireAssertion(ctx =>
            ctx.User.Claims
                .FirstOrDefault(c => c.Type == "age") is { } claim &&
                int.Parse(claim.Value) >= 18));
});

// Resource-based authorization
public class DocumentAuthorizationHandler 
    : AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext ctx,
        OperationAuthorizationRequirement requirement,
        Document resource)
    {
        if (resource.OwnerId == ctx.User.FindFirstValue(ClaimTypes.NameIdentifier))
            ctx.Succeed(requirement);
        return Task.CompletedTask;
    }
}

Q35. What is ASP.NET Core Identity? Medium

builder.Services.AddIdentity<ApplicationUser, IdentityRole>(opts => {
    opts.Password.RequireDigit = true;
    opts.Password.RequiredLength = 8;
    opts.Lockout.MaxFailedAccessAttempts = 5;
    opts.Lockout.LockoutTimeSpan = TimeSpan.FromMinutes(15);
    opts.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();

// User management
await _userManager.CreateAsync(user, password);
await _userManager.AddToRoleAsync(user, "Admin");
var result = await _signInManager.PasswordSignInAsync(email, password, isPersistent, lockoutOnFailure: true);

Q36. What is HTTPS and HSTS? Easy

// Force HTTPS redirect
app.UseHttpsRedirection();

// HTTP Strict Transport Security (HSTS) header
// Tells browsers to always use HTTPS for this domain
app.UseHsts();
// appsettings.json: "Hsts": { "MaxAge": 365, "IncludeSubDomains": true }

Q37. What is anti-forgery in ASP.NET Core? Medium

// For MVC forms (prevents CSRF)
builder.Services.AddAntiforgery();

// In Razor view
@Html.AntiForgeryToken()

// Validate
[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult Submit(FormModel model) { }

// Minimal API
app.MapPost("/submit", [ValidateAntiForgeryToken] (FormModel form) => { });

Q38. What is data protection in ASP.NET Core? Advanced

// ASP.NET Core's built-in encryption/decryption
var provider = DataProtectionProvider.Create("MyApp");
var protector = provider.CreateProtector("purpose");

var protected = protector.Protect("sensitive-data");
var original = protector.Unprotect(protected);

// Time-limited tokens
var timeLimited = protector.ToTimeLimitedDataProtector();
var token = timeLimited.Protect("data", TimeSpan.FromMinutes(5));

Q39. What is SignalR? Advanced

// Real-time WebSocket communication
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
    
    public async Task SendToGroup(string group, string msg)
    {
        await Clients.Group(group).SendAsync("NewMessage", msg);
    }
}

// Register
builder.Services.AddSignalR();
app.MapHub<ChatHub>("/chathub");

Advanced Topics

Q40. What is gRPC in ASP.NET Core? Advanced

// .proto file
service UserService {
    rpc GetUser (UserRequest) returns (UserResponse);
    rpc ListUsers (ListRequest) returns (stream UserResponse);
}

// Generated service
public class UserGrpcService : UserService.UserServiceBase
{
    public override async Task<UserResponse> GetUser(
        UserRequest request, ServerCallContext context)
    {
        var user = await _repo.GetById(request.Id);
        return new UserResponse { Id = user.Id, Name = user.Name };
    }
}

builder.Services.AddGrpc();
app.MapGrpcService<UserGrpcService>();

Q41. What is IMemoryCache vs IDistributedCache? Medium

// IMemoryCache: in-process, single server
_cache.Set("key", value, TimeSpan.FromMinutes(5));
_cache.TryGetValue("key", out var cached);

// IDistributedCache: Redis, SQL Server, multi-server
await _cache.SetStringAsync("key", json, new DistributedCacheEntryOptions {
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
});
var val = await _cache.GetStringAsync("key");

Q42. What is Health Checks? Medium

builder.Services.AddHealthChecks()
    .AddSqlServer(connectionString)
    .AddRedis(redisUrl)
    .AddUrlGroup(new Uri("https://external-api.com/health"), "external");

app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready", new HealthCheckOptions {
    Predicate = check => check.Tags.Contains("ready")
});

Q43. What is output caching (.NET 7+)? Advanced

builder.Services.AddOutputCache(opts => {
    opts.AddBasePolicy(builder => builder.Cache());
    opts.AddPolicy("Users", builder => builder.Tag("users").Expire(TimeSpan.FromMinutes(5)));
});

app.UseOutputCache();

[OutputCache(PolicyName = "Users")]
[HttpGet]
public async Task<IActionResult> GetUsers() { }

// Invalidate by tag
await _cache.EvictByTagAsync("users", ct);

Q44. What is the repository pattern? Advanced

public interface IUserRepository
{
    Task<User?> GetByIdAsync(int id);
    Task<IEnumerable<User>> GetAllAsync();
    Task<User> CreateAsync(User user);
    Task UpdateAsync(User user);
    Task DeleteAsync(int id);
}

public class UserRepository : IUserRepository
{
    private readonly AppDbContext _context;
    public UserRepository(AppDbContext context) => _context = context;
    
    public async Task<User?> GetByIdAsync(int id) =>
        await _context.Users.FindAsync(id);
}

// Register
builder.Services.AddScoped<IUserRepository, UserRepository>();

Q45. Predict the output: Medium

builder.Services.AddScoped<ICounter, Counter>();
// Counter: int count = 0; void Increment() => count++; int Value => count;

// Two injections in same request
public class TestController(ICounter c1, ICounter c2) : ControllerBase
{
    [HttpGet]
    public IActionResult Test()
    {
        c1.Increment(); c1.Increment();
        c2.Increment();
        return Ok(new { c1 = c1.Value, c2 = c2.Value });
    }
}

Output: {"c1": 3, "c2": 3}

Explanation: ICounter is Scoped - same instance per request. c1 and c2 refer to the same object. Three increments total.


Mock Interview: 5 Questions

  1. Explain the ASP.NET Core middleware pipeline and draw the request/response flow.
  2. What is the difference between AddScoped, AddSingleton, and AddTransient? When should you use each?
  3. How do you prevent N+1 query issues in EF Core?
  4. Implement JWT token generation and validation for a REST API.
  5. What is the difference between IActionResult, ActionResult<T>, and returning a concrete type?

FAQ

Q: Do I need C# knowledge for ASP.NET Core interviews? A: Yes. ASP.NET Core interviews test C# async/await, LINQ, generics, and interfaces. Review C# fundamentals alongside this guide.

Q: Is ASP.NET Core good for microservices? A: Yes. ASP.NET Core is one of the fastest web frameworks for microservices. Minimal APIs, gRPC support, and native Docker support make it competitive with Go and Node.js for high-performance services.

Q: Should I learn Blazor for .NET web development? A: Learn Web API first for backend roles. Blazor is a valid choice for .NET full-stack (both server-side Blazor and WebAssembly), but the job market for Blazor is smaller than React/Angular/Vue for frontend work.


Related reading: Java Interview Questions 2026 | Spring Framework Interview Questions 2026 | Docker Interview Questions 2026 | SQL Interview Questions 2026

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: