Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Middleware is a component in the HTTP request pipeline that can:
Middleware can:
Middleware executes in the order it's added in Program.cs.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<YourMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers();
});
app.Run();
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
app.UseMiddleware<YourMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllers(); });
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
app.Map
Method Description
app.Use Adds middleware that can call next in the
pipeline.
app.UseMiddlewar
e<T>()
Adds a custom middleware class.
app.Run Terminal middleware – does not call next. Ends
the pipeline.
app.Map Branches the pipeline based on URL path (e.g.
/api).
Example:
app.Use(async (context, next) => {
await next(); // go to next middleware
});
app.Run(async context => {
await context.Response.WriteAsync("Hello World"); //
terminates pipeline
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Create a class with:
public class MyCustomMiddleware
private readonly RequestDelegate _next;
public MyCustomMiddleware(RequestDelegate next) => _next =
next;
public async Task InvokeAsync(HttpContext context)
// Pre-processing logic
await _next(context);
// Post-processing logic
Register it:
app.UseMiddleware<MyCustomMiddleware>();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
RequestDelegate is a delegate representing the next middleware in the
pipeline:
public delegate Task RequestDelegate(HttpContext context);
In custom middleware, it allows passing control to the next component.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Middleware is executed in the order it's added, and this order affects
behavior.
Example:
app.UseAuthentication(); // Must come before authorization
app.UseAuthorization();
app.UseEndpoints(...);
Logging, error handling, and security middlewares must be early
in the pipeline.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Simply don’t call await next() in a middleware:
if (!context.User.Identity.IsAuthenticated)
context.Response.StatusCode = 401;
return; // Short-circuits
await next(); // only called if authenticated
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
app.UseStaticFiles() enables serving files from wwwroot.
Important: It must be added before routing or endpoints so static files
are served without invoking controller logic.
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(...);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
(UseExceptionHandler, UseDeveloperExceptionPage)
only).
a custom page or handler.
Example:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
Or inline:
app.UseExceptionHandler(errorApp =>
errorApp.Run(async context =>
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An error
occurred");
});
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Redirects HTTP requests to HTTPS.
app.UseHttpsRedirection();
Add early in the pipeline, before auth or routing.
You can configure HTTPS ports in launchSettings.json or
appsettings.json.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
app.UseStaticFiles(new StaticFileOptions
FileProvider = new
PhysicalFileProvider(Path.Combine(env.ContentRootPath,
"MyFiles")),
RequestPath = "/Files",
OnPrepareResponse = ctx =>
ctx.Context.Response.Headers.Append("Cache-Control",
"public,max-age=600");
});
For directory browsing:
app.UseDirectoryBrowser(new DirectoryBrowserOptions
FileProvider = new PhysicalFileProvider("path"),
RequestPath = "/browse"
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
middleware
Type Description
Terminal Ends the pipeline. Doesn’t call next(). E.g., app.Run()
Non-Termi
nal
Calls next() and allows other middlewares to run after it.
E.g., app.Use()
Terminal middleware:
app.Run(async ctx => {
await ctx.Response.WriteAsync("This ends the pipeline");
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
app.UseAuthentication(); // Validates user identity
app.UseAuthorization(); // Applies policies/roles
Order matters: must be after routing but before endpoints.
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(...);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
builder.Services.AddCors(options =>
options.AddPolicy("MyPolicy", policy =>
policy.WithOrigins("
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("MyPolicy");
Must be placed before routing/endpoints.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
execution time)
Example custom middleware to measure time:
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);
sw.Stop();
Console.WriteLine($"Request took
{sw.ElapsedMilliseconds} ms");
Register:
app.UseMiddleware<TimingMiddleware>();
Dependency Injection (DI)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Dependency Injection (DI) is a design pattern that allows you to inject dependencies
(services) into classes instead of hard-coding them.
🔹 Promotes loose coupling
🔹 Enhances testability
🔹 Encourages separation of concerns
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
✅ Capabilities:
⚠ Limitations:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Lifetime Description Use Case Example
Transient New instance every time Lightweight stateless
services
Scoped One instance per request Database context, UoW
Singleto
One instance for the app's
lifetime
Logging, Config access
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public void ConfigureServices(IServiceCollection services)
services.AddTransient<IMyService, MyService>();
services.AddScoped<IRepository, Repository>();
services.AddSingleton<ILoggerService, LoggerService>();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IApplicationBuilder.ApplicationServices
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
logic or 3rd-party containers.
✅ Use constructor injection for immutability and clarity.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
using (var scope = serviceScopeFactory.CreateScope())
var scopedService =
scope.ServiceProvider.GetRequiredService<IMyScopedService>();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IServiceScopeFactory to resolve scoped services safely.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
To replace:
services.AddSingleton<IService, CustomImplementation>();
To remove:
var descriptor = services.First(x => x.ServiceType ==
typeof(IMyService));
services.Remove(descriptor);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IOptionsMonitor)
services.Configure<MySettings>(Configuration.GetSection("MySettings"
));
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
there
background.
IServiceScopeFactory.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IConfiguration is automatically registered and injected via constructor.
public MyService(IConfiguration config)
var key = config["MyKey"];
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core provides structured logging via ILogger<T>.
public class MyService
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger) => _logger = logger;
public void DoSomething() => _logger.LogInformation("Action
performed");
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Occurs when two services depend on each other directly or indirectly.
🛠 Fix:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use a mocking framework like Moq:
var mockService = new Mock<IMyService>();
mockService.Setup(s => s.Get()).Returns("test");
var controller = new MyController(mockService.Object);
Mocking helps isolate the unit of work and test behavior independently.
MVC & Razor Pages
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
How does it differ from MVC in
“older” ASP.NET?
🔹 Key differences in ASP.NET Core:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
When to use Razor Pages instead of
MVC?
ASP.NET Core 2.0.
controller combined).
✅ Use Razor Pages for:
✅ Use MVC for:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
}");
/Pages/Products/Edit.cshtml.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
a view or JSON).
with code-behind).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Tag Helpers: Use HTML-like syntax. Easier to read/maintain.
<form asp-controller="Home" asp-action="Login"></form>
HTML Helpers: C# methods used in Razor.
@Html.BeginForm("Login", "Home")
✅ Prefer Tag Helpers in modern ASP.NET Core apps.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Purpose
ViewDa
Current
request
No Pass data to views
ViewBa
Current
request
Yes ViewData wrapper
(dynamic)
TempD
ata
Across
requests
No Preserved for 1 redirect
only
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
model properties.
public IActionResult Submit(User user) { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Decorate model properties:
public class User {
[Required]
[EmailAddress]
public string Email { get; set; }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public IEnumerable<ValidationResult>
Validate(ValidationContext context)
public class MyCustomAttribute : ValidationAttribute {
public override bool IsValid(object value) { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
_Layout.cshtml.
public class CartViewComponent : ViewComponent {
public IViewComponentResult Invoke() => View("Cart",
model);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
return View(model); // Strongly typed
ViewBag.Message = "Hello";
ViewData["Count"] = 5;
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public class LogActionFilter : IActionFilter { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public class IndexModel : PageModel {
public void OnGet() { ... }
public IActionResult OnPost() { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public IndexModel(IMyService service) { ... }
@inject ILogger<MyPage> Logger
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
dotnet new razorclasslib
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Customer).
[Area("Admin")]
public class DashboardController : Controller { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
app.UseStaticFiles();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IViewEngine.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
@inject IViewLocalizer Localizer
<h1>@Localizer["Welcome"]</h1>
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
large, modular apps.
Web API (RESTful Services)
Web API (RESTful Services)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
How to design RESTful APIs in ASP.NET Core
REST (Representational State Transfer) is an architectural style for
building scalable web services. RESTful APIs follow standard HTTP
methods (GET, POST, PUT, DELETE) and stateless communication.
✅ Key principles for RESTful API in ASP.NET Core:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
The [ApiController] attribute is used to denote Web API controllers in
ASP.NET Core.
✅ Benefits:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
templates)
[Route("api/products")]
[ApiController]
public class ProductsController : ControllerBase {
[HttpGet("{id}")]
public IActionResult Get(int id) { ... }
Use placeholders like {id}, constraints like {id:int}.
You can also define route prefixes at controller level and use relative routes
in actions.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
media type versioning)
Use Microsoft.AspNetCore.Mvc.Versioning package.
✅ Supported methods:
application/vnd.company.v1+json
services.AddApiVersioning(options => {
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core selects the response format based on the Accept header.
services.AddControllers()
.AddXmlSerializerFormatters();
Accept: application/xml
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
form
Source Attribute
Body [FromBody
Query
string
[FromQuer
Route [FromRout
Form
data
[FromForm
Header [FromHear
ASP.NET Core infers the source when possible.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Request.Body for streaming.
Enable buffering or streaming to avoid memory overload.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use UseExceptionHandler middleware or custom ExceptionMiddleware.
You can also create a global error handler:
app.UseExceptionHandler(config => {
config.Run(async context => {
// Log and return problem details
});
});
Or use ProblemDetails for structured error responses.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use proper status codes:
return Ok(result);
return NotFound();
return BadRequest(ModelState);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public ActionResult<Product> Get(int id) { ... }
Prefer ActionResult<T> for simpler, strongly-typed APIs.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
NotFound() : Ok(product);
✅ Improves scalability and performance.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Enable CORS (Cross-Origin Resource Sharing) to allow client apps from
different domains:
services.AddCors(options => {
options.AddPolicy("AllowFrontend", builder =>
builder.WithOrigins("
.AllowAnyHeader()
.AllowAnyMethod());
});
app.UseCors("AllowFrontend");
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core doesn't include rate limiting out of the box (pre-.NET 8).
Use libraries like:
.NET 8 introduced built-in RateLimiterMiddleware.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use Swashbuckle.AspNetCore or NSwag for generating Swagger docs.
services.AddSwaggerGen();
app.UseSwagger();
app.UseSwaggerUI();
Supports:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
+ HttpClient.
var client = _factory.CreateClient();
var response = await client.GetAsync("/api/products");
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
services.AddAuthentication(JwtBearerDefaults.AuthenticationSch
eme)
.AddJwtBearer(options => { ... });
[Authorize(Roles = "Admin")]
providers.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ValidateAntiForgeryToken)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
CreateMap<Product, ProductDto>();
var dto = _mapper.Map<ProductDto>(product);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Example with EF Core:
modelBuilder.Entity<Product>()
.Property(p => p.RowVersion).IsRowVersion();
Return 409 Conflict if concurrency exception is caught.
Model Binding & Validation
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Model binding in ASP.NET Core maps incoming HTTP data to C# parameters or model
properties.
🔍 Sources considered:
ASP.NET Core automatically binds data based on parameter types and attributes
([FromBody], [FromQuery], etc.).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
form fields.
or JSON body.
public IActionResult Create([FromBody] Product product)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use a custom model binder when default binding doesn’t work (e.g., custom formats,
headers).
public class CustomBinder : IModelBinder {
public Task BindModelAsync(ModelBindingContext context) {
// Custom logic here
Register with [ModelBinder] or globally in Startup.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
[FromQuery], etc.)
You cannot bind multiple [FromBody] parameters in a single action.
Common sources:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Decorate models with attributes:
public class User {
[Required]
[StringLength(50)]
[EmailAddress]
public string Email { get; set; }
Used in both MVC and API for validation.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Client-side validation improves UX, but server-side is essential for security.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Create custom rules by inheriting ValidationAttribute:
public class MustBeEvenAttribute : ValidationAttribute {
public override bool IsValid(object value) {
return (int)value % 2 == 0;
Use like:
[MustBeEven]
public int Number { get; set; }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use for cross-field validation within a model:
public class Product : IValidatableObject {
public string Name { get; set; }
public decimal Price { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext
context) {
if (Price < 0) {
yield return new ValidationResult("Price must be
positive");
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
public class UserValidator : AbstractValidator<User> {
public UserValidator() {
RuleFor(x => x.Email).NotEmpty().EmailAddress();
Register with:
services.AddFluentValidationAutoValidation();
✅ Offers more readable and testable validation logic than data annotations.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ModelState.IsInvalid.
ModelState.IsValid.
if (!ModelState.IsValid) return View(model);
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Used to check if bound model passed validation:
if (!ModelState.IsValid) {
return BadRequest(ModelState);
MVC automatically adds errors to ModelState based on validation attributes.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core supports binding nested properties:
public class Order {
public Customer Customer { get; set; }
public List<Product> Products { get; set; }
Works seamlessly from JSON or form data if property names match.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Model binding does not sanitize input — it binds raw data.
🛡 To prevent attacks (XSS, injection), sanitize:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Used for file uploads from forms (not [FromBody]):
public IActionResult Upload(IFormFile file)
var path = Path.Combine("uploads", file.FileName);
using var stream = new FileStream(path, FileMode.Create);
file.CopyTo(stream);
📝 For multiple files:
List<IFormFile> files
Configuration & AppSettings
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Development, Production).
🔧 ASP.NET Core loads them automatically based on the environment:
ASPNETCORE_ENVIRONMENT=Development
✅ Loaded in order of precedence, where later files override earlier ones.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Production)
ASP.NET Core uses the ASPNETCORE_ENVIRONMENT variable to determine the runtime
environment.
Supported environments (by convention):
Environment-specific logic can be applied:
if (env.IsDevelopment()) { ... }
Also used to load:
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
✅ ASP.NET Core supports hierarchical override of config sources:
MyApp__Logging__LogLevel__Default=Warning
dotnet run --Logging:LogLevel:Default=Debug
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Inject IConfiguration anywhere:
public class MyService {
private readonly string _apiKey;
public MyService(IConfiguration config) {
_apiKey = config["MySettings:ApiKey"];
You can also access nested settings via config.GetSection("MySettings").
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Bind config to strongly typed objects:
public class MySettings {
public string ApiKey { get; set; }
public int Timeout { get; set; }
services.Configure<MySettings>(config.GetSection("MySettings"));
Use via IOptions<MySettings>.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
IOptionsMonitor<T>)
services.
public MyService(IOptions<MySettings> options) {
var settings = options.Value;
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
dotnet user-secrets init
dotnet user-secrets set "MySettings:ApiKey" "secret"
builder.Configuration.AddAzureKeyVault(...);
✅ Secure sensitive data like API keys, connection strings, tokens.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
In appsettings.json:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
Supports built-in providers: Console, Debug, EventSource, Azure, etc.
Custom configuration through ILogger<T>.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Stored under "ConnectionStrings" section in appsettings.json:
"ConnectionStrings": {
"DefaultConnection":
"Server=.;Database=AppDb;Trusted_Connection=True;"
Read via:
var conn = config.GetConnectionString("DefaultConnection");
Or inject via Options pattern.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
JSON files support live reload:
builder.Configuration.AddJsonFile("appsettings.json", optional:
false, reloadOnChange: true);
IOptionsMonitor<T> automatically updates bound values when config changes.
🔁 Does not work with all sources (e.g., env vars, command line).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Using POCOs and Options pattern allows type-safe config:
services.Configure<MySettings>(config.GetSection("MySettings"));
Use [Required], [Range], etc., to add validation.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
You can validate bound config using IValidateOptions<T>:
public class MySettingsValidator : IValidateOptions<MySettings> {
public ValidateOptionsResult Validate(string name, MySettings
options) {
if (string.IsNullOrWhiteSpace(options.ApiKey)) {
return ValidateOptionsResult.Fail("ApiKey is
required.");
return ValidateOptionsResult.Success;
Register with DI:
services.AddSingleton<IValidateOptions<MySettings>,
MySettingsValidator>();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core supports multiple configuration providers:
Each can be chained with priority.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
✅ Best practices:
_logger.LogInformation("Token: {Token}", Mask(token));
Authentication & Authorization
(JWT, Identity)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
action (What are you allowed to do?)
In ASP.NET Core, both are handled via middleware and attributes like [Authorize], roles,
and policies.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core Identity provides a complete solution for:
✅ Setup:
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
In Startup or Program.cs:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
JWT (JSON Web Token) is a compact, URL-safe token format used for authentication.
✅ Configure JWT auth:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new
TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret"))
});
Use [Authorize] to secure endpoints.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
✅ Role-based:
[Authorize(Roles = "Admin")]
✅ Policy-based:
services.AddAuthorization(options => {
options.AddPolicy("CanEdit", policy =>
policy.RequireClaim("EditPermission"));
});
Then use:
[Authorize(Policy = "CanEdit")]
Policy-based gives more flexibility (custom requirements, claims, logic).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Used in traditional MVC apps for session-based auth.
services.AddAuthentication(CookieAuthenticationDefaults.Authenticati
onScheme)
.AddCookie(options => {
options.LoginPath = "/Account/Login";
});
On login:
await HttpContext.SignInAsync(principal);
Cookies are stored in the browser and sent with each request.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Use built-in providers:
services.AddAuthentication()
.AddGoogle(options => {
options.ClientId = "...";
options.ClientSecret = "...";
});
Also supports:
Use RemoteAuthenticationHandler<T> or Identity scaffolding.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Used with JWT to renew access tokens after expiration without logging in again.
You must manually implement refresh token logic (not built-in to Identity).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
✅ Configure expiration:
Expires = DateTime.UtcNow.AddMinutes(30)
✅ Use refresh tokens to handle expiration.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Example:
[Authorize]
public IActionResult Dashboard() { }
[AllowAnonymous]
public IActionResult Login() { }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Define complex authorization rules using IAuthorizationHandler:
public class MinimumAgeRequirement : IAuthorizationRequirement {
public int Age { get; }
public MinimumAgeRequirement(int age) => Age = age;
public class MinimumAgeHandler :
AuthorizationHandler<MinimumAgeRequirement> {
protected override Task HandleRequirementAsync(...) {
// logic
Register in DI and use with [Authorize(Policy = "...")].
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core uses Data Protection API to:
Configure:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("path"))
.SetApplicationName("AppName");
Used internally by Identity and cookie middleware.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Multi-tenancy can involve:
Strategies:
Can integrate with IdentityServer4 or Azure AD B2C for federated auth.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core Identity uses PBKDF2 hashing by default.
Best practices:
Use:
PasswordHasher<T>.HashPassword(user, password)
Can switch to Argon2, Bcrypt via custom password hasher.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Supported out of the box in ASP.NET Core Identity.
Options:
Enable via Identity configuration:
services.Configure<IdentityOptions>(options => {
options.SignIn.RequireConfirmedEmail = true;
});
Use SignInManager<T> to handle verification and token generation.
Filters & Middleware Overlaps
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Filters are components that run code before or after certain stages in the request pipeline
within MVC or Razor Pages. Types of filters include:
Filters allow you to inject logic at these specific points.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
request.
handlers.
scoped to MVC processing.
for concerns around controller/action execution.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Filters run in a specific order depending on their type:
Within each type, filters can be ordered by their Order property and whether they are global,
controller-level, or action-level.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Create a custom filter by implementing one of the filter interfaces like:
public class CustomActionFilter : IActionFilter
public void OnActionExecuting(ActionExecutingContext context)
// Before action executes
public void OnActionExecuted(ActionExecutedContext context)
// After action executes
Register globally in Startup:
services.AddControllersWithViews(options =>
options.Filters.Add<CustomActionFilter>();
});
Or decorate controllers/actions:
[ServiceFilter(typeof(CustomActionFilter))]
public class HomeController : Controller { ... }
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
options.
actions.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Filters receive context objects (e.g., ActionExecutingContext) providing:
This allows filters to inspect, modify, or block processing at their stage.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Filters can short-circuit by setting the result early, preventing further execution:
public void OnActionExecuting(ActionExecutingContext context)
if (!IsAuthorized())
context.Result = new UnauthorizedResult(); // stops pipeline
here
This prevents action execution and later filters from running.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
limited DI capabilities.
resolved from DI container, enabling constructor injection.
Use service-based filters when you need dependencies injected.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
authentication).
validation, caching).
MVC-specific exceptions and returning appropriate views or API responses.
Versioning, CORS
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
api-version=1.0)
Use the Microsoft.AspNetCore.Mvc.Versioning NuGet package:
services.AddApiVersioning(options => {
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Semantic versioning (semver) uses MAJOR.MINOR.PATCH format, e.g., 1.2.0.
Version negotiation allows clients and servers to agree on an API version via headers or
URL. Servers should support multiple versions and respond with supported version info.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts web
pages from making requests to a different domain than the one that served the web page, to
prevent cross-site attacks.
CORS defines a way for servers to allow controlled access to resources from a different
origin.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Configure in Startup.cs or Program.cs:
services.AddCors(options =>
options.AddPolicy("AllowSpecificOrigin",
builder =>
builder.WithOrigins("
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Enable middleware:
app.UseCors("AllowSpecificOrigin");
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
headers), browsers send an OPTIONS request first, called a preflight.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
pipeline with app.UseCors(...).
[EnableCors("PolicyName")] or [DisableCors] attributes on controllers or
actions.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
builder.WithOrigins("
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
Cross‑Cutting / Advanced / “Miscellaneous”
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
fast.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
(w3wp.exe), better performance.
it.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
compression
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
deployments.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
boosts.
Scenario / Design & Best Practices
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
architecture, onion architecture)
logic), Domain (entities, business rules), Infrastructure (data access, external
services).
towards the domain layer.
pointing inward.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
not implementations.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
migrations)
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
injection, XSS etc)
Sample / Misc Interview Questions
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
HTTP response (Ok, NotFound, Redirect, etc.).
data or an HTTP response. Improves clarity and enables better OpenAPI docs.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
registration and middleware setup with a simplified, top-level statement style.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
controller classes.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
versions.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
applied globally.
([Route], [HttpGet]).
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
types
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
error responses
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
configure them
KestrelServerOptions.Limits.MaxRequestBodySize.
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
ASP.NET Core ASP.NET Core Tutorial · ASP.NET Core
deserialization).