Top ASP.NET Core Interview Questions

ASP.NET CoreStartup.csConfiguration
The Startup.cs file configures the application's services and request pipeline. It contains: ConfigureServices (Registers services like dependency injection) and Configure (Defines the middleware pipeline).
Example:
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
}

ASP.NET CoreFeaturesFramework
Key features include: Cross-platform support, Built-in dependency injection, Modular middleware pipeline, High performance with Kestrel, Support for Razor Pages, MVC, and Minimal APIs, Configuration system (e.g., appsettings.json), Integrated logging and diagnostics, Support for cloud and containerized deployments.

ASP.NET CoreASP.NET FrameworkComparison
ASP.NET Core is a cross-platform, open-source framework for building modern web applications and APIs, designed to be lightweight and modular. Unlike ASP.NET Framework, which runs only on Windows and is tightly coupled to System.Web, ASP.NET Core supports Linux, macOS, and Windows, uses a modular architecture, and is optimized for cloud and microservices. Differences: Platform (ASP.NET Framework is Windows-only; ASP.NET Core is cross-platform), Performance (ASP.NET Core is faster), Modularity (ASP.NET Core uses NuGet packages), Hosting (ASP.NET Core can run on Kestrel or IIS).
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello, ASP.NET Core!");
app.Run();

ASP.NET CoreDependency InjectionService Configuration
Dependency Injection (DI) is a design pattern for providing dependencies to classes, promoting loose coupling. ASP.NET Core has built-in DI, configured in ConfigureServices.
Example:
public interface IMyService
{
    string GetData();
}

public class MyService : IMyService
{
    public string GetData() => "Hello from MyService";
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped();
        services.AddControllers();
    }
}

public class MyController : ControllerBase
{
    private readonly IMyService _service;
    public MyController(IMyService service)
    {
        _service = service;
    }

    [HttpGet]
    public IActionResult Get() => Ok(_service.GetData());
}

ASP.NET CoreRoutingConfiguration
Routing maps URLs to endpoints (e.g., controllers or Minimal APIs). It’s configured using UseRouting and Map methods or attributes in MVC.
Example:
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        return Ok($"Product {id}");
    }
}

// Minimal API
app.MapGet("/products/{id}", (int id) => $"Product {id}");

ASP.NET CoreMiddlewareRequest Pipeline
Middleware components are software pieces in the request pipeline that handle HTTP requests and responses. They can process, modify, or terminate requests.
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Before\n");
    await next();
    await context.Response.WriteAsync("After\n");
});

app.Run(async context => await context.Response.WriteAsync("Hello\n"));

app.Run();

ASP.NET CoreAddTransientAddScopedAddSingletonDependency Injection
These are service lifetimes in ASP.NET Core DI: AddTransient (New instance per request), AddScoped (Same instance within a single HTTP request), AddSingleton (Same instance for the entire application lifetime).
Example:
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient();
    services.AddScoped();
    services.AddSingleton();
}

ASP.NET Coreappsettings.jsonConfiguration
appsettings.json is a JSON file for storing configuration settings (e.g., connection strings, API keys). It’s loaded into the configuration system and supports environment-specific files (e.g., appsettings.Development.json).
Example:
{
  "MySettings": {
    "ApiKey": "my-secret-key"
  }
}

ASP.NET CoreModel BindingMVC
Model binding maps HTTP request data (e.g., query strings, form data) to action method parameters or model objects.
Example:
public class UserModel
{
    public string Name { get; set; }
}

public class UserController : ControllerBase
{
    [HttpPost]
    public IActionResult Create([FromBody] UserModel model)
    {
        return Ok($"Created user: {model.Name}");
    }
}

ASP.NET CoreConfigurationAccessing Values
Configuration values are accessed via IConfiguration or strongly-typed options using the Options pattern.
Example:
public class MyController : ControllerBase
{
    private readonly IConfiguration _config;
    public MyController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var apiKey = _config["MySettings:ApiKey"];
        return Ok(apiKey);
    }
}

// Options Pattern
public class MySettings
{
    public string ApiKey { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{
    services.Configure(Configuration.GetSection("MySettings"));
}

public class MyController : ControllerBase
{
    private readonly MySettings _settings;
    public MyController(IOptions options)
    {
        _settings = options.Value;
    }

    [HttpGet]
    public IActionResult Get() => Ok(_settings.ApiKey);
}

ASP.NET CoreService ContainerDependency Injection
The service container manages dependency injection, resolving and providing registered services. It’s built into ASP.NET Core via IServiceCollection.
Example:
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped();
}

ASP.NET CoreTag HelpersRazor
Tag Helpers enhance HTML in Razor views, providing server-side logic and cleaner syntax compared to HTML helpers.
Example:
@model MyModel

ASP.NET CoreJSONController
Use Ok(), Json(), or return a model that’s automatically serialized to JSON.
Example:
public class MyController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var data = new { Name = "Test", Id = 1 };
        return Ok(data); // Returns JSON
    }
}

ASP.NET CoreIActionResultActionResultMVC
IActionResult is a general interface for action results (e.g., Ok, NotFound). ActionResult is strongly-typed, allowing direct return of a model or IActionResult.
Example:
public class MyController : ControllerBase
{
    [HttpGet]
    public ActionResult Get()
    {
        return "Hello"; // ActionResult
    }

    [HttpGet("other")]
    public IActionResult GetOther()
    {
        return Ok("Hello"); // IActionResult
    }
}

ASP.NET CoreException HandlingError Management
Exception handling is managed using try-catch blocks, middleware (e.g., UseExceptionHandler), or filters.
Example:
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var error = context.Features.Get();
        await context.Response.WriteAsync($"Error: {error.Error.Message}");
    });
});

// Filter
public class CustomExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new ObjectResult("Error occurred")
        {
            StatusCode = 500
        };
        context.ExceptionHandled = true;
    }
}

ASP.NET CoreUseStaticFilesMiddleware
UseStaticFiles() serves static files (e.g., images, CSS, JavaScript) from the wwwroot folder.
Example:
app.UseStaticFiles();

ASP.NET CoreFiltersMVC
Filters run code before or after specific stages in the request pipeline (e.g., authorization, action execution). Types include Authorization, Action, Result, and Exception filters.
Example:
public class LogFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        Console.WriteLine("Before action");
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        Console.WriteLine("After action");
    }
}

[LogFilter]
public class MyController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("Test");
}

ASP.NET CoreKestrelWeb Server
Kestrel is a cross-platform, high-performance web server for ASP.NET Core, handling HTTP requests. It can run standalone or behind a reverse proxy like IIS.
Example:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel();
var app = builder.Build();
app.Run();

ASP.NET CoreProgram.csHosting Model
In .NET 6/7, Program.cs configures the entire application (services, middleware, hosting) using the minimal hosting model, replacing Startup.cs.
Example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped();

var app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();

ASP.NET CoreCORSSecurity
CORS (Cross-Origin Resource Sharing) is enabled using middleware to allow cross-origin requests.
Example:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", builder =>
        {
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowAll");
    app.UseRouting();
    app.UseEndpoints(endpoints => endpoints.MapControllers());
}