0 0
Read Time:4 Minute, 14 Second

📌 1. Startup.cs in ASP.NET Core

Definition

Startup.cs is the central configuration file for your ASP.NET Core application, used to register services and define the middleware pipeline.

📍 Where is it used?

  • In every ASP.NET Core project (.NET 5 or earlier).

  • Configures DI (Dependency Injection), routing, authentication, etc.

⚙️ How is it used?

  • By implementing two methods: ConfigureServices() and Configure().

🎯 Why is it used?

  • To define the behavior of the app at startup: dependencies, middleware, etc.

💼 Code Example

public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IMyService, MyService>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}

🎤 Interview Questions & Answers

Q1: What is the difference between ConfigureServices and Configure?
A: ConfigureServices registers services for DI, while Configure builds the middleware pipeline for handling HTTP requests.

Q2: Can we have multiple Startup.cs files?
A: Yes, by using environment-specific Startup classes like StartupDevelopment.cs and defining them in Program.cs.

Q3: How is Startup.cs linked to the app’s lifecycle?
A: It’s automatically invoked during app bootstrapping by the host builder.


📂 2. appsettings.json – The Configuration File

Definition

appsettings.json stores app-level configurations like DB connection strings, keys, and logging levels.

📍 Where is it used?

  • Found at the root of every ASP.NET Core project.

  • Accessed via IConfiguration.

⚙️ How is it used?

  • Values are injected using Configuration["key"] or via strongly typed objects.

🎯 Why is it used?

  • To externalize and separate configuration from code.

💼 Code Example

{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=True;"
},
"Jwt": {
"Key": "SecretKey123",
"Issuer": "MyApp"
}
}
csharp
// Reading from appsettings.json
string connStr = Configuration.GetConnectionString("DefaultConnection");
string jwtKey = Configuration["Jwt:Key"];

🎤 Interview Questions & Answers

Q1: How do you access strongly typed configuration values?
A: Use services.Configure<T>(Configuration.GetSection("SectionName")) and inject IOptions<T> in your class.

Q2: How do you manage multiple environments (dev/staging/prod)?
A: By creating appsettings.Development.json, appsettings.Production.json, etc., and setting ASPNETCORE_ENVIRONMENT.

Q3: What happens if a key is missing?
A: Configuration["missingKey"] returns null—handle null-checks or use fallback values.


🧰 3. Filters in ASP.NET Core

Definition

Filters allow you to execute logic at specific points during request processing, like before or after controller actions.

📍 Where are they used?

  • Global level: applied to all controllers.

  • Controller level or action level.

  • Common in logging, authentication, and error handling.

⚙️ How are they used?

  • By implementing IActionFilter, IExceptionFilter, or using built-in attributes.

🎯 Why are they used?

  • To separate concerns like logging and error handling from business logic.

💼 Code Example

public class LogActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("Action started");
}
public void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine(“Action ended”);
}
}

// Registering the filter globally
services.AddControllers(options => {
options.Filters.Add<LogActionFilter>();
});

🎤 Interview Questions & Answers

Q1: What is the difference between middleware and filters?
A: Middleware applies globally and works outside MVC, while filters are scoped to MVC and can access action context.

Q2: Can filters be async?
A: Yes, by implementing IAsyncActionFilter.

Q3: When to use a filter vs. middleware?
A: Use filters when you need access to ModelState, action parameters, or result metadata.


🧾 4. The using Keyword in C#

Definition

using is used for:

  1. Importing namespaces.

  2. Managing resources that implement IDisposable.

📍 Where is it used?

  • Every C# file starts with using directives.

  • using statements are used for disposable resources like DB connections, file streams.

⚙️ How is it used?

  • Namespace imports allow usage of classes like HttpClient, DbContext, etc.

  • Statement ensures resource cleanup.

🎯 Why is it used?

  • Prevents memory leaks by auto-disposing resources.

  • Organizes code with external dependencies.

💼 Code Example

// 1. Namespace import
using System.Net.Http;
// 2. Resource disposal
using (var client = new HttpClient())
{
var response = await client.GetStringAsync(“https://example.com”);
}

// Modern using declaration (C# 8+)
using var file = new FileStream("log.txt", FileMode.OpenOrCreate);

🎤 Interview Questions & Answers

Q1: What’s the difference between using directive and statement?
A: Directive brings in namespaces; statement ensures object disposal.

Q2: What happens if you don’t use using with IDisposable?
A: The resource may stay in memory longer than needed, causing memory leaks or file locks.

Q3: How is using internally implemented?
A: It’s translated into a try-finally block where Dispose() is called in the finally.


🧠 Quick Recap Table

Concept Where Used How Used Why Used
Startup.cs Entry of ASP.NET Core project Register services, build middleware pipeline App bootstrapping and lifecycle config
appsettings.json Root configuration file Read via Configuration["key"] Manage environments and external config
Filters Global, Controller, or Action level Implement interfaces or use attributes Decouple logging, validation, auth logic
using Top of file / disposable object scope Namespace import and resource management Avoid memory leaks, improve readability

📣 Conclusion

Understanding how Startup.cs, appsettings.json, Filters, and using work together gives you a strong foundation in ASP.NET Core development. These are the hidden pillars that bring performance, maintainability, and structure to your enterprise application.

Previous post Technical Architect vs. Solutions Architect: Understanding the Differences, Career Paths, and Real-Time Examples
Next post Understanding Frontend Development from Inception to Innovation
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Close
0
Would love your thoughts, please comment.x
()
x