.NET Core Interview Questions and Answers

Find 100+ .NET Core interview questions and answers to assess candidates’ skills in C#, ASP.NET Core, and microservices. Hire top .NET developers with ease!
By
WeCP Team

As .NET Core continues to be a leading framework for building high-performance, scalable applications in 2025, recruiters must identify developers who can effectively work within its ecosystem. With its cross-platform capabilities, modular architecture, and cloud-native support, .NET Core is a preferred choice for modern web and enterprise applications.

This resource, "100+ .NET Core Interview Questions and Answers," is designed to help recruiters evaluate candidates efficiently. It covers essential topics ranging from fundamentals to advanced concepts such as dependency injection, middleware, asynchronous programming, microservices, and integration with cloud services.

Whether hiring junior developers or experienced engineers, this guide enables you to assess a candidate’s:

  • Core .NET Core Knowledge: Request handling, middleware, dependency injection, and configuration management.
  • Advanced Skills: Entity Framework Core, background services, logging, and security best practices.
  • Real-World Proficiency: Performance optimization, debugging, and deployment on Docker, Kubernetes, and Azure.

For a streamlined assessment process, consider platforms like WeCP, which allow you to:

Create tailored .NET Core assessments based on job roles.
Include real-world coding challenges and scenario-based questions.
Conduct remote proctored tests to maintain assessment integrity.
Leverage AI-powered analysis for quick and accurate evaluation.

Save time, improve hiring efficiency, and confidently recruit .NET Core developers who can build robust, scalable applications from day one.

100+ .NET Core Interview Questions

.NET Core Interview Questions for Beginner Level

  1. What is .NET Core, and how is it different from the .NET Framework?
  2. How do you install .NET Core SDK?
  3. What is the purpose of the dotnet new command?
  4. How does .NET Core support cross-platform development?
  5. What are the main benefits of using .NET Core for application development?
  6. What is the role of the Common Language Runtime (CLR) in .NET Core?
  7. Explain the structure of a .NET Core project.
  8. What is the difference between dotnet run and dotnet build commands?
  9. How do you create a new ASP.NET Core MVC project from scratch?
  10. What is Kestrel, and why is it used in .NET Core?
  11. How does .NET Core support dependency injection?
  12. Explain what middleware is in ASP.NET Core.
  13. How does routing work in ASP.NET Core MVC?
  14. What is an API controller, and how does it differ from an MVC controller in .NET Core?
  15. What is appsettings.json, and how do you configure settings in it?
  16. What is Entity Framework Core, and what is its primary use?
  17. How do you connect a .NET Core application to a SQL Server database?
  18. How does the IConfiguration interface work in .NET Core?
  19. What are NuGet packages, and how are they used in .NET Core projects?
  20. Explain how you handle errors using try-catch in .NET Core.
  21. What is the role of the Program.cs file in a .NET Core project?
  22. What is Startup.cs, and what are its responsibilities?
  23. How do you enable HTTPS in a .NET Core application?
  24. How do you implement basic logging in .NET Core?
  25. What is model binding in ASP.NET Core MVC?
  26. Explain what ViewData, ViewBag, and TempData are in ASP.NET Core.
  27. How do you implement validation in ASP.NET Core using data annotations?
  28. What is a RESTful API, and how do you build one using ASP.NET Core?
  29. How do you consume a Web API in a .NET Core application?
  30. How do you manage cookies in an ASP.NET Core application?
  31. What are filters in ASP.NET Core?
  32. How do you handle user authentication in an ASP.NET Core application?
  33. What is Razor, and how is it used in ASP.NET Core MVC?
  34. How do you serve static files in a .NET Core application?
  35. What is the ViewComponent in ASP.NET Core MVC?
  36. How do you return JSON data from a controller in ASP.NET Core?
  37. How do you perform file uploads in ASP.NET Core?
  38. What are Tag Helpers in ASP.NET Core?
  39. How do you publish a .NET Core application?
  40. What are global exception handlers, and how do you implement them in .NET Core?

.NET Core Interview Questions for Intermediate Level

  1. How do you implement Dependency Injection (DI) in .NET Core?
  2. What are the different service lifetimes in ASP.NET Core (Transient, Scoped, Singleton)?
  3. How do you register services in the Startup.cs file in .NET Core?
  4. Explain the difference between IActionResult and ActionResult in an ASP.NET Core controller.
  5. What is model validation, and how do you handle it in ASP.NET Core MVC?
  6. How do you implement exception handling globally in a .NET Core application?
  7. How do you use custom middleware in ASP.NET Core?
  8. What is the role of IHostedService in background tasks in .NET Core?
  9. How do you configure and use CORS (Cross-Origin Resource Sharing) in a .NET Core application?
  10. What is the purpose of AddMvc() and how does it differ from AddControllers() in .NET Core?
  11. How do you implement session management in .NET Core?
  12. Explain the repository pattern and how you implement it in .NET Core.
  13. How do you perform CRUD operations using Entity Framework Core?
  14. What is lazy loading, and how is it implemented in Entity Framework Core?
  15. How do you use migrations in Entity Framework Core to update your database?
  16. Explain the difference between eager loading and lazy loading in Entity Framework Core.
  17. How do you create and consume a Web API in .NET Core?
  18. How do you secure Web APIs in ASP.NET Core using JWT (JSON Web Tokens)?
  19. How do you enable role-based authorization in ASP.NET Core?
  20. How do you manage state in a stateless ASP.NET Core application?
  21. How do you use AutoMapper in .NET Core?
  22. How do you work with asynchronous programming in .NET Core using async and await?
  23. What is Swagger, and how do you set it up in a .NET Core Web API project?
  24. How do you configure database connections in .NET Core for SQL Server or another database?
  25. What is In-Memory Caching, and how do you use it in .NET Core?
  26. How do you implement distributed caching in a .NET Core application?
  27. What is the purpose of UseEndpoints() in ASP.NET Core?
  28. How do you use Dependency Injection in unit testing for .NET Core applications?
  29. What are Action Filters in ASP.NET Core, and how do they work?
  30. How do you implement rate limiting in an ASP.NET Core Web API?
  31. How do you configure logging providers (e.g., Serilog, NLog) in a .NET Core application?
  32. What are background services in .NET Core, and how do you use them?
  33. How do you implement a health check endpoint in a .NET Core application?
  34. What are Hosted Services in .NET Core, and how do they differ from standard services?
  35. How do you work with RabbitMQ or other message brokers in .NET Core?
  36. How do you implement token-based authentication in .NET Core?
  37. How do you integrate Identity Server with .NET Core for authentication?
  38. How do you enable response caching in .NET Core Web APIs?
  39. How do you manage connection pooling for high-performance databases in .NET Core?
  40. How do you handle concurrency in Entity Framework Core?

.NET Core Interview Questions for Experienced Level

  1. What is the CQRS (Command Query Responsibility Segregation) pattern, and how do you implement it in .NET Core?
  2. How do you handle distributed transactions in a microservice architecture using .NET Core?
  3. How do you implement the Event Sourcing pattern in .NET Core?
  4. Explain the Saga pattern for handling distributed transactions in .NET Core microservices.
  5. How do you integrate .NET Core with Docker, and what are the benefits?
  6. How do you handle logging in microservices using centralized logging in .NET Core?
  7. How do you implement Polly for handling transient faults in .NET Core applications?
  8. How do you integrate gRPC in a .NET Core application for inter-service communication?
  9. What are the best practices for optimizing performance in high-traffic .NET Core applications?
  10. How do you implement Circuit Breaker and Retry patterns using Polly in .NET Core?
  11. How do you manage caching at scale for distributed applications in .NET Core?
  12. How do you deploy a .NET Core application to a Kubernetes cluster?
  13. How do you handle API versioning in an ASP.NET Core Web API?
  14. How do you integrate OAuth2 and OpenID Connect in a .NET Core application?
  15. How do you implement hybrid transactions across microservices in .NET Core?
  16. How do you secure microservices using JWT and Identity Server in .NET Core?
  17. What is GraphQL, and how do you implement it in .NET Core?
  18. How do you scale an ASP.NET Core application using Azure Kubernetes Service (AKS)?
  19. How do you handle message-driven microservices using RabbitMQ in .NET Core?
  20. How do you implement distributed tracing in a .NET Core microservice architecture?
  21. How do you implement zero-downtime deployments for .NET Core applications in production?
  22. How do you work with Azure Functions in a .NET Core application?
  23. How do you handle large file uploads and downloads in a .NET Core Web API?
  24. What are the different strategies for scaling out microservices in .NET Core?
  25. How do you optimize SQL queries using Dapper in .NET Core?
  26. How do you handle concurrency conflicts in a multi-user Entity Framework Core application?
  27. How do you implement a global exception handler for microservices in .NET Core?
  28. How do you implement authentication using Active Directory and Azure AD in .NET Core?
  29. How do you secure a .NET Core application with HTTPS and certificates?
  30. How do you integrate ElasticSearch with .NET Core for full-text search capabilities?
  31. How do you implement API Gateway in a microservices architecture with .NET Core?
  32. What is Orleans, and how do you use it in .NET Core for distributed systems?
  33. How do you implement JWT refresh tokens securely in a .NET Core Web API?
  34. How do you optimize memory management and garbage collection in .NET Core for high-performance applications?
  35. How do you handle multitenancy in an ASP.NET Core application?
  36. How do you configure load balancing for .NET Core applications running on Kubernetes?
  37. How do you monitor performance and health in a production .NET Core application?
  38. How do you implement WebSockets for real-time communication in ASP.NET Core?
  39. How do you integrate message queues like Azure Service Bus in a .NET Core application?
  40. How do you architect a microservice-based solution using .NET Core for cloud-native applications?

.NET Core Interview Questions and Answers in 2025

.NET Core Interview Questions and Answers for Freshers/Beginners

1. What is .NET Core, and how is it different from the .NET Framework?

.NET Core is a cross-platform, high-performance framework for building modern cloud-based, internet-connected applications. Unlike the .NET Framework, which runs only on Windows, .NET Core supports Windows, macOS, and Linux, making it more versatile for cross-platform development.

2. How do you install .NET Core SDK?

You can download the .NET Core SDK from the official .NET website. Follow the installation guide for your specific operating system (Windows, macOS, or Linux).

3. What is the purpose of the dotnet new command?

The dotnet new command creates a new .NET Core project with a specific template (e.g., console app, web app, etc.). For example, dotnet new console creates a new console application.

4. How does .NET Core support cross-platform development?

.NET Core is designed to be platform-independent. It uses a runtime (CoreCLR) that can run on different operating systems. The same .NET Core application can run on Windows, macOS, and Linux without modification.

5. What are the main benefits of using .NET Core for application development?

  1. Cross-platform support (Windows, macOS, Linux)
  2. High performance and scalability
  3. Modern development (support for cloud, microservices)
  4. Open-source and community-driven
  5. Unified development (build web, desktop, mobile, and cloud apps)

6. What is the role of the Common Language Runtime (CLR) in .NET Core?

The CLR is the runtime environment in .NET Core that manages the execution of .NET applications, providing services like memory management, exception handling, and garbage collection.

7. Explain the structure of a .NET Core project.

A typical .NET Core project contains files like Program.cs (entry point), Startup.cs (configuration), and appsettings.json (configuration settings). It also includes directories like Controllers, Views, wwwroot, and dependencies listed in the csproj file.

8. What is the difference between dotnet run and dotnet build commands?

  1. dotnet build compiles the application without running it.
  2. dotnet run compiles and runs the application.

9. How do you create a new ASP.NET Core MVC project from scratch?

Run the command dotnet new mvc -n ProjectName to create a new ASP.NET Core MVC project. Then, navigate to the project directory and run dotnet run to launch the project.

10. What is Kestrel, and why is it used in .NET Core?

Kestrel is a cross-platform web server for ASP.NET Core applications. It is used to serve HTTP requests and can run behind other web servers like IIS or Nginx, or as a standalone server.

11. How does .NET Core support dependency injection?

.NET Core has built-in support for dependency injection (DI) through the IServiceCollection and IServiceProvider interfaces. You can register services in the Startup.cs file using methods like AddSingleton, AddScoped, and AddTransient.

12. Explain what middleware is in ASP.NET Core.

Middleware is software that handles requests and responses in an ASP.NET Core application. Middleware components are executed in a pipeline, where each component can either pass the request to the next component or terminate the pipeline.

13. How does routing work in ASP.NET Core MVC?

Routing in ASP.NET Core MVC maps incoming requests to controller actions. Routes are defined in the Startup.cs file, typically using the UseEndpoints or MapControllerRoute methods.

14. What is an API controller, and how does it differ from an MVC controller in .NET Core?

API controllers are specifically used for building Web APIs. They return data (e.g., JSON) rather than views. API controllers use the [ApiController] attribute to enable features like automatic model validation.

15. What is appsettings.json, and how do you configure settings in it?

appsettings.json is a configuration file used in .NET Core applications to store settings like database connection strings, environment settings, and more. You can access these settings through the IConfiguration interface in .NET Core.

16. What is Entity Framework Core, and what is its primary use?

Entity Framework Core (EF Core) is an Object-Relational Mapping (ORM) framework that allows developers to interact with databases using .NET objects, eliminating the need for most SQL queries.

17. How do you connect a .NET Core application to a SQL Server database?

Add a connection string to appsettings.json, then configure it in Startup.cs using the AddDbContext method. You can then inject the DbContext into your application to interact with the database.

18. How does the IConfiguration interface work in .NET Core?

The IConfiguration interface provides access to configuration settings, allowing you to read key-value pairs from files like appsettings.json, environment variables, or command-line arguments.

19. What are NuGet packages, and how are they used in .NET Core projects?

NuGet is a package manager for .NET. NuGet packages are libraries that you can add to your project to use third-party or shared code. You can install them via the dotnet add package command.

20. Explain how you handle errors using try-catch in .NET Core.

The try-catch block is used to handle exceptions. You place the code that might throw an exception inside the try block and handle the exception in the catch block.

21. What is the role of the Program.cs file in a .NET Core project?

Program.cs is the entry point of a .NET Core application. It contains the Main method, which starts the application by calling CreateHostBuilder and setting up the host.

22. What is Startup.cs, and what are its responsibilities?

Startup.cs configures the services and the request pipeline for the application. It defines the ConfigureServices method for DI configuration and Configure method for request processing pipeline configuration.

23. How do you enable HTTPS in a .NET Core application?

To enable HTTPS, configure your project to use HTTPS in launchSettings.json. Also, add middleware like UseHttpsRedirection in the Startup.cs file.

24. How do you implement basic logging in .NET Core?

.NET Core provides built-in logging support through the ILogger interface. You can inject ILogger into controllers or services and log information using methods like LogInformation, LogWarning, and LogError.

25. What is model binding in ASP.NET Core MVC?

Model binding is the process of mapping incoming request data (such as form data or query parameters) to action method parameters.

26. Explain what ViewData, ViewBag, and TempData are in ASP.NET Core.

  1. ViewData: A dictionary for passing data from controller to view.
  2. ViewBag: A dynamic wrapper around ViewData for easier access to data.
  3. TempData: Used to store data temporarily between two requests, typically after a redirect.

27. How do you implement validation in ASP.NET Core using data annotations?

Data annotations are attributes applied to model properties to enforce validation. For example, [Required], [Range], and [StringLength] are used for validation. These attributes are checked automatically by the model binder.

28. What is a RESTful API, and how do you build one using ASP.NET Core?

A RESTful API follows REST principles like stateless communication, resource representation, and HTTP methods. You can create a RESTful API in ASP.NET Core by creating controllers that return data (usually JSON) and use HTTP methods like GET, POST, PUT, and DELETE.

29. How do you consume a Web API in a .NET Core application?

You can use HttpClient to consume a Web API. Create an instance of HttpClient, send a request using GetAsync or PostAsync, and process the response.

30. How do you manage cookies in an ASP.NET Core application?

You can manage cookies using the HttpContext.Response.Cookies.Append method to set cookies and HttpContext.Request.Cookies to read them.

31. What are filters in ASP.NET Core?

Filters allow you to run code before or after an action method executes. Examples include authorization filters, resource filters, action filters, and exception filters.

32. How do you handle user authentication in an ASP.NET Core application?

ASP.NET Core supports authentication through Identity, JWT, or OAuth. You configure authentication in Startup.cs and use middleware to handle login, registration, and token validation.

33. What is Razor, and how is it used in ASP.NET Core MVC?

Razor is a templating engine used to generate dynamic HTML in MVC views. It allows you to embed C# code into HTML using the @ symbol.

34. How do you serve static files in a .NET Core application?

Use the Use Static Files middleware in Startup. cs to serve static files from the www root folder.

35. What is the View Component in ASP.NET Core MVC?

A View Component is a reusable component that renders part of a page. It is similar to partial views but allows for more complex logic.

36. How do you return JSON data from a controller in ASP.NET Core?

Return a JSON result from an action method using return J son(object) or return Ok(object) in an API controller.

37. How do you perform file uploads in ASP.NET Core?

Use the I Form File interface to handle file uploads. In the controller, read the uploaded file, process it, and save it to a specified location.

38. What are Tag Helpers in ASP.NET Core?

Tag Helpers are server-side components that generate HTML and provide a way to interact with Razor views. Examples include asp-for, asp-controller, and asp-action.

39. How do you publish a .NET Core application?

Use the dotnet publish command to compile and package the application for deployment. You can also specify the target runtime (e.g., Windows, Linux) during the publishing process.

40. What are global exception handlers, and how do you implement them in .NET Core?

Global exception handling can be implemented using middleware. You create custom middleware that catches exceptions and handles them centrally, ensuring that all unhandled exceptions are captured.

.NET Core Interview Questions and Answers for Intermediates

1. How do you implement Dependency Injection (DI) in .NET Core?

Dependency Injection (DI) is a design pattern used to implement IoC (Inversion of Control), allowing you to manage the dependencies of classes. In .NET Core, DI is a first-class citizen, and the framework provides built-in support for it.

To implement DI in .NET Core:

Register services: You define the service in the Startup.cs file, inside the ConfigureServices method. You can register services with different lifetimes like Transient, Scoped, or Singleton.

Example:

public void ConfigureServices(IServiceCollection services)
{
    // Register IMyService with MyService as a dependency
    services.AddTransient<IMyService, MyService>();
}
  1. AddTransient: A new instance of the service is created every time it is requested.
  2. AddScoped: The same instance is used within a request, but different instances are created for different requests.
  3. AddSingleton: A single instance is used throughout the application's lifetime.

Inject services: You inject the registered services into a class, typically via the constructor.

Example:

public class MyController : Controller
{
    private readonly IMyService _myService;

    // Constructor Injection
    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        var result = _myService.DoSomething();
        return View(result);
    }
}

Resolve services: The framework automatically resolves and provides the dependency at runtime based on what’s registered in the service container.

This approach reduces tight coupling, improves testability (by injecting mock services in unit tests), and makes your code cleaner and more maintainable.

2. What are the different service lifetimes in ASP.NET Core (Transient, Scoped, Singleton)?

In ASP.NET Core, services can be registered with different lifetimes, depending on how they should behave during the application's lifecycle. There are three main lifetimes:

Transient:

  1. A new instance of the service is created each time it is requested.
  2. Best for lightweight, stateless services where each request requires a fresh instance.

Example:

services.AddTransient<IMyService, MyService>();

Use case: For services that maintain a global state, such as configuration settings or logging mechanisms.

Choosing the right lifetime depends on the service's behavior and how it manages state. For instance, services that don’t need to share state should be transient, while services that manage state for the application should be singletons.

3. How do you register services in the Startup .cs file in .NET Core?

In ASP.NET Core, service registration is handled within the Configure Services method in the Startup. cs file. You use the I Service Collection interface to register your dependencies. There are three common types of service lifetimes: Transient, Scoped, and Singleton (as described above), and each type is registered by calling a corresponding method on I Service Collection.

Example of registering services:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Register a transient service
        services.AddTransient<IEmailService, EmailService>();

        // Register a scoped service
        services.AddScoped<IUserService, UserService>();

        // Register a singleton service
        services.AddSingleton<ILogger, Logger>();

        // Register framework services
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure the middleware pipeline
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Steps:

  1. Define the interface and implementation classes: These classes define the service logic.
  2. Add them to IServiceCollection in ConfigureServices: Register each service with its appropriate lifetime (AddTransient, AddScoped, AddSingleton).
  3. Inject them where needed: Once registered, you can inject these services into controllers, other services, or middleware using constructor injection.

This approach ensures that your application’s dependencies are centralized and easy to manage, while supporting the core principles of DI and IoC.

4. Explain the difference between IActionResult and ActionResult in an ASP.NET Core controller.

Both IActionResult and ActionResult are used as return types for ASP.NET Core controller actions, but there are some key differences:

IActionResult:

  1. IActionResult is an interface that represents a wide variety of possible return types for controller actions.
  2. It allows for greater flexibility as it can represent any type that implements IActionResult, such as ViewResult, JsonResult, RedirectResult, ContentResult, etc.

Example:

public IActionResult MyAction()
{
    return View();  // ViewResult
}

Action Result:

  1. Action Result is a concrete class that inherits from IAction Result. It provides additional helper methods like Ok(), BadRequest(), NotFound(), etc.
  2. Using Action Result provides more specific types for returning standardized HTTP responses.

Example:

public ActionResult MyAction()
{
    return Ok();  // Returns a 200 OK status with a response body.
}

When to use which?

  • Use IActionResult when you want more flexibility and the method could return various response types.
  • Use ActionResult when you specifically want to return HTTP status code responses like Ok, BadRequest, NotFound.

5. What is model validation, and how do you handle it in ASP.NET Core MVC?

Model validation is the process of ensuring that incoming data from HTTP requests conforms to the rules defined in your data models. ASP.NET Core provides a built-in mechanism to validate models using data annotations.

Defining validation rules: Use data annotations to apply validation rules to your model properties:

public class UserModel
{
    [Required(ErrorMessage = "Username is required")]
    [StringLength(50, MinimumLength = 3, 
    ErrorMessage = "Username must be between 3 and 50 characters")]
    public string Username { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid email format")]
    public string Email { get; set; }
}

Handling validation in the controller: In your controller action, you can check if the model is valid using ModelState.IsValid:

public IActionResult Register(UserModel userModel)
{
    if (ModelState.IsValid)
    {
        // Process the valid model
        return RedirectToAction("Success");
    }

    // If the model is invalid, return the same view with validation messages
    return View(userModel);
}

Displaying validation messages in the view: In the Razor view, use HTML helpers to display validation messages:

<form asp-action="Register">
    <input asp-for="Username" />
    <span asp-validation-for="Username" class="text-danger"></span>

    <input asp-for="Email" />
    <span asp-validation-for="Email" class="text-danger"></span>

    <button type="submit">Register</button>
</form>

Custom validation attributes: If the built-in validation attributes are not sufficient, you can create custom validation attributes by inheriting from Validation Attribute:

public class CustomValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid
    (object value, ValidationContext validationContext)
    {
        // Custom logic
        return ValidationResult.Success;
    }
}

Model validation ensures that data is clean and reliable before it is processed by the application, helping to prevent errors and inconsistencies.

6. What is Middleware in ASP.NET Core? How does it work?

Middleware in ASP.NET Core is software that sits between the incoming HTTP request and the outgoing HTTP response. It is responsible for handling and processing HTTP requests, and each piece of middleware can either:

  • Process the request and generate a response, or
  • Pass the request to the next middleware in the pipeline.

Middleware components are executed in the order they are registered in the Startup.cs file, and each one has the option to terminate the request by generating its own response or delegate the request to the next middleware.

Example:

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Middleware to log requests
        app.Use(async (context, next) =>
        {
            Console.WriteLine("Incoming Request: " + context.Request.Path);
            await next.Invoke(); // Pass to the next middleware
            Console.WriteLine("Outgoing Response: " + context.Response.StatusCode);
        });

        // Static files middleware
        app.UseStaticFiles();

        // Routing middleware
        app.UseRouting();

        // Endpoint middleware
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

In this example, the first middleware logs the request and response. It calls next.Invoke() to pass control to the next middleware in the pipeline (static files, routing, etc.).

Middleware is highly customizable and plays a central role in configuring the HTTP request pipeline in ASP.NET Core.

7. Explain the concept of Routing in ASP.NET Core.

Routing in ASP.NET Core is a mechanism to map incoming HTTP requests to the appropriate controller actions or endpoints. Routing can be convention-based or attribute-based.

Convention-based routing: You define routing patterns in the Startup.cs file using UseRouting() and UseEndpoints(). The routing pattern can include parameters for controllers, actions, and route variables.

Example:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

This routing pattern maps requests to the appropriate controller and action, with an optional id parameter.

Attribute routing: You can use attributes to define routing directly on controllers or actions. This allows for more fine-grained and flexible routing.

Example:

[Route("products")]
public class ProductsController : Controller
{
    [Route("details/{id}")]
    public IActionResult Details(int id)
    {
        // Return product details based on id
        return View();
    }
}

This route will match /products/details/{id}, where id is a route parameter.

Routing is a key component in directing incoming requests to the right controller or action, and ASP.NET Core allows you to mix both convention-based and attribute-based routing in the same application.

8. How do you handle exceptions in ASP.NET Core?

ASP.NET Core provides several mechanisms for handling exceptions: Developer Exception Page: For development environments, you can use the developer exception page to display detailed error information.

This is useful for debugging.

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

Exception Handling Middleware: In production environments, you use exception handling middleware to catch and handle exceptions globally. You can redirect to a custom error page, log the error, or return a generic response.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (!env.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
}

In this case, any unhandled exceptions will be caught and the user will be redirected to the /Home/Error route.

Custom exception handling middleware: You can also create custom middleware to handle exceptions and log them.

app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (Exception ex)
    {
        // Log exception
        await context.Response.WriteAsync("An error occurred.");
    }
});

Global Exception Filters: In MVC, you can handle exceptions globally by using exception filters.

public class CustomExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new RedirectToActionResult("Error", "Home", null);
    }
}

This filter can be applied globally to handle exceptions in all actions and controllers.

Exception handling ensures that errors are properly logged, and users are presented with user-friendly error messages instead of seeing raw exception details.

9. What is the difference between I Application Builder. Use and I Application Builder. Run in ASP.NET Core?

In ASP.NET Core, both Use and Run are methods used to add middleware to the HTTP request pipeline, but they serve different purposes.

Use:

  1. Use allows you to execute a piece of middleware and then pass control to the next middleware in the pipeline using next().
  2. It is useful when you want to perform some action and still allow subsequent middleware to run.

Example:

app.Use(async (context, next) =>
{
    // Perform some logic
    Console.WriteLine("Inside Use Middleware");

    await next(); // Pass control to the next middleware
});

Run:

  1. Run is a terminal middleware. Once Run is called, the pipeline is short-circuited, and no further middleware will be executed.

Example:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from Run Middleware");
});

In this case, no other middleware registered after Run will be executed, as Run terminates the pipeline.

Key difference:

  • Use allows the request to flow through the pipeline, invoking subsequent middleware, while Run terminates the pipeline after it is executed.

10. What are Filters in ASP.NET Core MVC? What are the types of filters?

Filters in ASP.NET Core MVC are used to execute custom logic before or after certain stages in the request pipeline, such as before an action is executed or after a result is returned. Filters provide a way to implement cross-cutting concerns like logging, authorization, caching, and exception handling.There are several types of filters:

Authorization Filters:

  1. Run before the action is executed to determine whether the user is authorized to execute the action.
  2. Example: [Authorize] attribute is an authorization filter.

Custom Authorization Filter:

public class CustomAuthFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // Custom authorization logic
    }
}

Action Filters:

  1. Run before or after the action method is executed.
  2. Use case: Logging or modifying input parameters.

Example:

public class CustomActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context) { }
    public void OnActionExecuted(ActionExecutedContext context) { }
}

Exception Filters:

  1. Handle exceptions thrown during the execution of an action or result.
  2. Use case: Logging errors or returning a custom error response.

Example:

public class CustomExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new RedirectToActionResult("Error", "Home", null);
    }
}

Result Filters:

  1. Run before or after the action result is executed.
  2. Use case: Modifying or processing the result before it's sent to the client.

Example:

public class CustomResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context) { }
    public void OnResultExecuted(ResultExecutedContext context) { }
}

Filters provide a way to inject custom behavior at different stages of the request processing pipeline, making them useful for cross-cutting concerns like authentication, caching, or logging.

11. What are Tag Helpers in ASP.NET Core?

Tag Helpers in ASP.NET Core are used to extend the functionality of HTML elements in Razor views. They allow you to add server-side processing logic to HTML tags in a clean and readable way, making your Razor views more expressive and maintainable.Tag Helpers are processed on the server, and they help you build dynamic content while still working with familiar HTML syntax.

Example:

<a asp-controller="Home" asp-action="Index">Home</a>

In this example:

  • asp-controller="Home": Specifies the controller to be used.
  • asp-action="Index": Specifies the action to be invoked in the HomeController.

ASP.NET Core includes many built-in Tag Helpers, such as:

  • asp-for: Generates HTML input elements bound to model properties.
  • asp-action, asp-controller: Used to generate hyperlinks to actions.
  • asp-validation-for: Displays validation messages for form fields.

You can also create custom Tag Helpers by inheriting from the TagHelper base class.

Creating a custom Tag Helper:

public class EmailTagHelper : TagHelper
{
    public string Address { get; set; }
    public string Display { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a"; // Replaces <email> with <a> tag
        output.Attributes.SetAttribute("href", $"mailto:{Address}");
        output.Content.SetContent(Display);
    }
}

Then, in your Razor view:

<email address="info@domain.com" display="Contact Us"></email>

Tag Helpers are a powerful feature of ASP.NET Core that provide a clean way to generate dynamic content within Razor views, helping to separate presentation from logic.

12. How does ASP.NET Core support Cross-Origin Resource Sharing (CORS)?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to prevent unauthorized access to resources from different origins (domains). ASP.NET Core provides built-in support for configuring CORS policies to allow or restrict cross-origin requests.

  1. Enable CORS in Startup.cs: You need to configure CORS in the Startup.cs file by using the services.AddCors() method inside ConfigureServices and applying CORS policies in Configure().

Example:

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

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors("AllowSpecificOrigin");  // Apply the policy
        app.UseRouting();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
}

In this example:

  • The policy "AllowSpecificOrigin" only allows requests from https://example.com.
  • AllowAnyHeader() allows all HTTP headers.
  • AllowAnyMethod() allows all HTTP methods (GET, POST, PUT, etc.).

Allowing CORS for All Origins: To allow requests from any origin, use the following:

builder.AllowAnyOrigin();

Applying CORS Globally or to Specific Controllers: You can apply CORS globally or only to specific controllers/actions using the [EnableCors] attribute.

[EnableCors("AllowSpecificOrigin")]
public class MyController : Controller
{
    // Action methods
}

CORS is essential for securing web applications and ensuring that only trusted domains can access your resources.

13. What is View Model in ASP.NET Core MVC? How is it different from a Model?

In ASP.NET Core MVC, a View Model is a class that represents the data and logic required specifically for the view. It is designed to transfer data between the controller and the view, and is often a combination of multiple models or properties tailored for the view's needs. Difference between View Model and Model:

Model:

  1. Represents the domain or business logic of the application.
  2. Contains data and validation rules for entities like User, Product, etc.
  3. Used to interact with the database through ORM frameworks like Entity Framework.

ViewModel:

  1. A custom class designed for the view, containing only the data needed for display or user interaction.
  2. Can include properties from multiple models, as well as additional logic or formatting specific to the view.
  3. Not tied to the database.

Example: If you have a User model:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

But your view needs both User information and some additional data like Role, you create a ViewModel:

public class UserViewModel
{
    public User User { get; set; }
    public string Role { get; set; }
}

This UserViewModel provides the data required by the view, combining user information with role data.

ViewModels help decouple the view from the business logic, ensuring that only the necessary data is passed to the view, improving maintainability and security.

14. What is Kestrel, and why is it used in ASP.NET Core?

Kestrel is a cross-platform web server for ASP.NET Core. It is the default web server included with ASP.NET Core and provides high performance for handling HTTP requests.

Key features of Kestrel:

  1. Cross-platform: Works on Windows, Linux, and macOS.
  2. Performance: Designed for high performance, Kestrel can handle a large number of requests efficiently.
  3. Lightweight: Kestrel is a lightweight server that is optimized for both development and production.

When to use Kestrel:

  • Kestrel can be used directly to serve ASP.NET Core applications during development and in production for scenarios where no additional reverse proxy (like IIS, Nginx, or Apache) is required.
  • For security and performance reasons, in a production environment, it is common to pair Kestrel with a reverse proxy like Nginx or IIS. The reverse proxy handles things like SSL termination, static file serving, and load balancing, while Kestrel manages dynamic content generation.

Example of configuring Kestrel in Program. cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();  // Configures Kestrel as the web server
                webBuilder.UseStartup<Startup>();
            });
}

Kestrel provides fast and lightweight server capabilities, making it ideal for serving ASP.NET Core applications.

15. How does ASP.NET Core support logging? What logging providers are available?

ASP.NET Core includes built-in support for logging to help developers capture and monitor events, errors, and application behavior. It provides a flexible and extensible logging framework that supports different logging providers.

Basic Logging Setup: Logging is configured in the Startup.cs file, and you can inject ILogger<T> into your classes to log messages.

Example:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Executing Index action");
        return View();
    }
}

Logging Levels: ASP.NET Core provides several logging levels that indicate the severity of a log message:

  1. Trace: Very detailed logs, used mainly for development.
  2. Debug: Less detailed than trace, typically used for development debugging.
  3. Information: General information about the application flow.
  4. Warning: Indication of a possible issue.
  5. Error: Errors that prevent the operation from continuing.
  6. Critical: Critical errors causing the application to crash.

Logging Providers: ASP.NET Core supports multiple logging providers to log data to different outputs:

  1. Console: Logs messages to the console.
  2. Debug: Logs messages to the Visual Studio output window.
  3. EventLog: Logs messages to the Windows Event Log (on Windows).
  4. Azure Application Insights: For cloud-based logging and performance monitoring.
  5. Third-party providers: Libraries like Serilog, NLog, and Log4Net can be integrated for advanced logging features.

Configure Logging in appsettings.json: You can configure logging settings (such as logging levels) in the appsettings.json file.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning"
        }
    }
}

ASP.NET Core provides a powerful and extensible logging framework that makes it easy to log messages, capture errors, and monitor application health using different logging providers.

16. What is Dependency Injection (DI) in ASP.NET Core?

Dependency Injection (DI) is a design pattern used in ASP.NET Core to achieve Inversion of Control (IoC), where the creation of dependencies (objects) is managed by an external component rather than the class that uses them. DI allows for better code maintainability, testability, and flexibility by promoting loose coupling between classes.ASP.NET Core has built-in support for DI, making it easy to inject dependencies into controllers, services, and other components.Types of Dependency Injection:

  1. Constructor Injection (most common): Dependencies are provided via the constructor.
  2. Method Injection: Dependencies are provided via method parameters.
  3. Property Injection: Dependencies are provided via public properties.

Example of Constructor Injection:

Service Interface:

public interface IEmailService
{
    void SendEmail(string to, string subject, string body);
}

Service Implementation:

public class EmailService : IEmailService
{
    public void SendEmail(string to, string subject, string body)
    {
        // Email sending logic
    }
}

Registering Service in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IEmailService, EmailService>();
    services.AddControllers();
}

Injecting Service in Controller:

public class HomeController : Controller
{
    private readonly IEmailService _emailService;

    public HomeController(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public IActionResult Index()
    {
        _emailService.SendEmail("example@domain.com", "Subject", "Body");
        return View();
    }
}

Lifetime of Services:

  • Transient: A new instance is created each time it is requested.
  • Scoped: A new instance is created per request.
  • Singleton: A single instance is created and shared throughout the application's lifetime.

17. What is the purpose of the Configure Services method in Startup. cs?

The Configure Services method in ASP.NET Core's Startup. cs file is used to configure the Dependency Injection (DI) container. It is where services are registered for use in the application. ASP.NET Core uses this method to register services such as MVC, custom services, middleware components, authentication services, database contexts, and more.

Example of Configure Services method:

public void ConfigureServices(IServiceCollection services)
{
    // Register MVC services
    services.AddControllersWithViews();
    
    // Register a custom service
    services.AddScoped<IEmailService, EmailService>();
    
    // Register a database context
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    // Add identity services for authentication
    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
}

In this example:

  • MVC services (AddControllersWithViews) are registered.
  • Custom services (IEmailService and EmailService) are registered with scoped lifetime.
  • A database context (ApplicationDbContext) is registered to use SQL Server.
  • Identity services are configured for authentication.

Once services are registered in ConfigureServices, they can be injected and used throughout the application via Dependency Injection.

18. What is the Configure method in Startup.cs used for in ASP.NET Core?

The Configure method in ASP.NET Core's Startup.cs file is used to define how the application will respond to incoming HTTP requests. It configures the middleware components that make up the HTTP request pipeline.

The order in which middleware components are added in the Configure method is critical because they are executed sequentially as the request flows through the pipeline.

Example of Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this example:

  • UseDeveloperExceptionPage: Shows detailed error information during development.
  • UseHttpsRedirection: Redirects HTTP requests to HTTPS.
  • UseStaticFiles: Enables serving static files (CSS, JS, images).
  • UseRouting: Enables routing to map requests to controllers and actions.
  • UseAuthentication and UseAuthorization: Enables authentication and authorization.
  • UseEndpoints: Defines the endpoints for the application, such as routing to controllers.

The Configure method sets up the middleware components that handle different stages of the request and response process.

19. What is the difference between AddScoped, AddTransient, and AddSingleton in ASP.NET Core?

In ASP.NET Core, service lifetimes define how long instances of services are kept in memory. When registering services in the DI container, you can specify one of three lifetimes: AddScoped, AddTransient, or AddSingleton.

AddTransient:

  • A new instance of the service is created each time it is requested.
  • Suitable for lightweight, stateless services.

Example:

services.AddTransient<IEmailService, EmailService>();

AddScoped:

  • A new instance is created once per request (i.e., the same instance is used throughout the entire request).
  • Useful for services that should maintain state or cache data for the duration of the request.

Example:

services.AddScoped<IUserService, UserService>();

AddSingleton:

  • A single instance is created once for the entire application lifetime (across all requests).
  • Suitable for services that are heavy to initialize or that should maintain a shared state.

Example:

services.AddSingleton<ILogger, Logger>();

Key differences:

  • Transient: A new instance is provided each time the service is requested.
  • Scoped: A new instance is provided per request.
  • Singleton: A single instance is shared across the entire application.

Choosing the correct service lifetime is crucial for optimizing memory usage and ensuring the correct behavior of your services.

20. How do you implement Authentication and Authorization in ASP.NET Core?

Authentication and Authorization are essential aspects of securing ASP.NET Core applications.

  1. Authentication:
    • Authentication is the process of verifying the user's identity (e.g., login credentials).
    • ASP.NET Core supports various authentication mechanisms such as cookies, JWT tokens, OAuth, and OpenID Connect.

Example of Cookie Authentication:

In Startup .cs, configure authentication in Configure Services:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
            });

    services.AddControllersWithViews();
}

In Configure, use app. Use Authentication() and app. Use Authorization():

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
  1. Authorization:
    • Authorization determines what actions a user can perform after their identity has been authenticated.
    • ASP.NET Core uses roles or claims for implementing authorization.

Example of Role-Based Authorization:

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

In this example, only users who belong to the "Admin" role can access the AdminController.

ASP.NET Core provides several built-in authorization mechanisms, including:

  • Role-based Authorization: Restrict actions to specific user roles.
  • Claims-based Authorization: Restrict actions based on specific claims or attributes of the user.

By combining authentication and authorization, you can effectively manage access control in ASP.NET Core applications.

21. What is the purpose of the IApplicationBuilder interface in ASP.NET Core?

The IApplicationBuilder interface is used to configure the HTTP request pipeline in ASP.NET Core applications. It provides methods to define middleware components that process requests and responses as they pass through the pipeline.

The IApplicationBuilder instance is available in the Configure method of Startup.cs, and it is used to register middleware components such as routing, authentication, and static file serving.

Key methods of I Application Builder:

  1. Use Routing: Sets up endpoint routing in the pipeline.
  2. Use Authentication: Adds authentication middleware for validating user credentials.
  3. Use Authorization: Adds authorization middleware to enforce access control based on user roles or claims.
  4. Use Endpoints: Defines the routing endpoints for controllers, Razor pages, etc.
  5. Use StaticFiles: Serves static files (CSS, JS, images, etc.) directly from the web root.

Example of I Application Builder in the Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this example, IApplicationBuilder is used to configure middleware components like error handling, HTTPS redirection, static file serving, routing, authentication, and authorization.

22. What is Middleware in ASP.NET Core, and how does it work?

Middleware in ASP.NET Core is software that is assembled into the application's request pipeline to handle requests and responses. Each middleware component can either process an incoming request and pass it to the next middleware in the pipeline or terminate the request by generating a response.

Middleware is executed in the order it is registered in the Configure method, which makes the order of middleware components critical.

Common ASP.NET Core middleware components:

  • UseRouting: Sets up endpoint routing.
  • UseAuthentication: Handles authentication.
  • UseAuthorization: Handles authorization based on user roles or claims.
  • UseStaticFiles: Serves static files like CSS, JavaScript, and images.
  • UseExceptionHandler: Handles exceptions globally.

Creating Custom Middleware: You can create custom middleware by implementing a class that takes an HttpContext object, processes the request, and either generates a response or passes the request to the next middleware component.

Example of custom middleware:

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Log the incoming request
        Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
        
        // Call the next middleware in the pipeline
        await _next(context);
        
        // Log the response
        Console.WriteLine($"Response: {context.Response.StatusCode}");
    }
}

To use this middleware, it is added to the request pipeline in the Configure method:

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<RequestLoggingMiddleware>();
}

Middleware in ASP.NET Core is an essential component for building modular and flexible request pipelines that can handle tasks like authentication, routing, and error handling.

23. How does the IHostingEnvironment interface help in configuring different environments in ASP.NET Core?

The IHostingEnvironment (or IWebHostEnvironment in later versions of ASP.NET Core) interface is used to provide information about the hosting environment of the application. This is helpful for configuring different settings or behaviors based on whether the application is running in Development, Staging, or Production.

Key properties of IWebHostEnvironment:

  1. EnvironmentName: The name of the current environment (e.g., "Development", "Staging", "Production").
  2. WebRootPath: The absolute path to the web root directory (typically wwwroot).
  3. ContentRootPath: The absolute path to the root of the content files (e.g., appsettings.json).

ASP.NET Core uses environment variables (like ASPNETCORE_ENVIRONMENT) to determine the current environment. By default, the environment is set to "Production" unless specified otherwise.

Example of using IWebHostEnvironment in Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();  // Only show detailed errors in Development
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");  // Use generic error page in Production
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
}

Configure different settings for different environments:

  • appsettings.json files can have environment-specific versions like appsettings.Development.json or appsettings.Production.json, which override default settings.

Example of loading different configurations based on the environment:

public void ConfigureServices(IServiceCollection services)
{
    if (env.IsDevelopment())
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
    }
    else
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ProdConnection")));
    }
}

Using IWebHostEnvironment allows you to configure your application differently based on the environment, which is essential for debugging, testing, and deploying in production.

24. What is the role of UseEndpoints in ASP.NET Core, and how does endpoint routing work?

UseEndpoints is a middleware component in ASP.NET Core that is used to define and configure the endpoints that the application will respond to. It works in conjunction with endpoint routing, which allows you to map incoming requests to specific controllers, actions, or Razor Pages.

Endpoint routing is a feature that helps manage how requests are routed to controllers and Razor Pages, making routing more flexible and extensible.

How UseEndpoints works:

  1. UseRouting: This middleware is responsible for matching the incoming request URL with the appropriate endpoint (controller, Razor Page, etc.).
  2. UseEndpoints: This middleware processes the matched endpoint and generates the response.

Example of using UseEndpoints in the request pipeline:

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

In this example, UseRouting enables routing to endpoints, and UseEndpoints defines the endpoints (in this case, mapping requests to controllers and actions).

Common Endpoint Mapping Methods:

  • MapControllerRoute: Routes requests to MVC controllers.
  • MapRazorPages: Routes requests to Razor Pages.
  • MapGet, MapPost, MapPut, etc.: Routes specific HTTP verbs to handlers.

Endpoint routing is a powerful feature of ASP.NET Core that helps you manage how HTTP requests are routed and handled in a structured and efficient way.

25. How does ASP.NET Core handle static files?

ASP.NET Core can serve static files (such as HTML, CSS, JavaScript, images, and fonts) directly from the file system without needing to pass through the MVC pipeline. The static files are typically stored in the wwwroot folder, which acts as the web root for the application.

To enable static file serving in ASP.NET Core, you need to use the UseStaticFiles middleware.

Example of serving static files:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();  // Enable static file serving
    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

By default, static files are served from the wwwroot directory. You can place static assets like CSS, JavaScript, and images inside wwwroot and reference them in your views.

Example:

<link rel="stylesheet" href="/css/site.css" />
<img src="/images/logo.png" alt="Logo" />

If you want to serve static files from a different directory or configure caching for static files, you can use additional options:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider
    (Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
    RequestPath = "/StaticFiles"
});

In this example, static files are served from the "MyStaticFiles" directory, and they are accessed via the /StaticFiles URL.

Handling static files in ASP.NET Core is simple and efficient, allowing for direct file serving with optional caching and customization options.

Here are the next five intermediate-level .NET Core interview questions and their detailed answers:

26. What is Kestrel in ASP.NET Core, and why is it used?

Kestrel is a cross-platform, high-performance, open-source web server built into ASP.NET Core. It is the default web server used to host ASP.NET Core applications.

Kestrel is designed to be lightweight and fast, making it suitable for serving applications directly in both development and production environments. However, for security reasons, it is often used behind a reverse proxy such as Nginx or IIS in production deployments.

Why Kestrel is used:

  1. Cross-platform support: It runs on Windows, Linux, and macOS.
  2. High performance: Kestrel is optimized for low-latency and high-throughput applications.
  3. Lightweight: It has a small memory footprint and minimal overhead.
  4. Concurrency: Kestrel can handle multiple connections and requests efficiently using libuv or the newer I/O APIs available in .NET.

How to configure Kestrel in Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();  // Configures the app to use Kestrel
                webBuilder.UseStartup<Startup>();
            });
}

You can configure Kestrel-specific options like SSL certificates, request limits, and port numbers in the ConfigureWebHostDefaults section.

Example of configuring Kestrel:

webBuilder.UseKestrel(options =>
{
    options.Listen(IPAddress.Loopback, 5001);  // Bind to a specific port
    options.Listen(IPAddress.Loopback, 5002, listenOptions =>
    {
        listenOptions.UseHttps
        ("path-to-certificate.pfx", "password");  // HTTPS configuration
    });
});

In production environments, Kestrel is typically used behind a reverse proxy for better security and scalability.

27. What is the purpose of appsettings.json in ASP.NET Core?

The appsettings.json file is used in ASP.NET Core to store configuration settings in a JSON format. This file is a convenient way to store settings like connection strings, API keys, application behavior, and environment-specific settings. It is a replacement for the web.config file used in previous ASP.NET versions.

Key features of appsettings.json:

  • Environment-specific configuration: You can have different versions of the settings file, such as appsettings.Development.json or appsettings.Production.json, which override or extend the base configuration.
  • Hierarchical structure: The settings are organized in a key-value structure, with support for nested sections.

Example of an appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServer;Database=myDB;
    User Id=myUser;Password=myPassword;"
  },
  "AppSettings": {
    "ApiKey": "12345",
    "ApiUrl": "https://api.example.com"
  }
}

Using appsettings.json in code: To access the settings, you inject the IConfiguration interface into your classes.

Example:

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;

    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        var apiKey = _configuration["AppSettings:ApiKey"];
        var apiUrl = _configuration["AppSettings:ApiUrl"];
        return View();
    }
}

In this example, the ApiKey and ApiUrl values from appsettings.json are accessed using IConfiguration.

appsettings.json provides a flexible, JSON-based way to manage configurations, and ASP.NET Core automatically loads and binds it to the IConfiguration object.

28. How can you read environment-specific settings from appsettings.{Environment}.json?

ASP.NET Core supports environment-specific configurations through additional configuration files, such as appsettings.Development.json or appsettings.Production.json. These files override the values defined in the default appsettings.json based on the current environment.

The current environment is determined by the ASPNETCORE_ENVIRONMENT environment variable. The common environment names are Development, Staging, and Production.

Steps to read environment-specific settings:

  1. Set the environment variable ASPNETCORE_ENVIRONMENT to "Development", "Staging", or "Production".
  2. Create an appsettings.{Environment}.json file to override or add settings for that specific environment.

Example of environment-specific appsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Debug"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;
    Database=myDevDB;User Id=myDevUser;Password=myDevPassword;"
  }
}

In the Startup class, the environment-specific file is automatically loaded and merged with appsettings.json:

Example of setting environment in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile
            ("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile
                  ($"appsettings.{env.EnvironmentName}.json", 
                  optional: true, reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

When the application is running in the Development environment, ASP.NET Core will automatically load appsettings.Development.json in addition to the default appsettings.json.

This mechanism allows you to easily manage settings that change between environments, like database connection strings, API keys, or logging levels.

29. What is ViewComponent in ASP.NET Core, and how is it different from a PartialView?

A ViewComponent in ASP.NET Core is a reusable component that encapsulates rendering logic, similar to a controller action but with the purpose of rendering a specific part of a view. ViewComponents are ideal for building complex UI components that may include their own logic and models, independent of the main page or view model.

Key features of ViewComponent:

  1. It is reusable across multiple views.
  2. It has its own logic and view.
  3. It doesn't participate in the MVC action pipeline but is invoked directly from a view.
  4. It can return HTML, JSON, or other formats.

Differences between ViewComponent and PartialView:

  • ViewComponent: Contains both rendering logic (C# code) and a view (UI part). It has its own model and can perform complex logic before rendering the view.
  • PartialView: Is purely a view (UI component) without any logic. It shares the model of the parent view.

Example of a ViewComponent:

Create the ViewComponent class:

public class RecentPostsViewComponent : ViewComponent
{
    private readonly IPostService _postService;

    public RecentPostsViewComponent(IPostService postService)
    {
        _postService = postService;
    }

    public async Task<IViewComponentResult> InvokeAsync(int count)
    {
        var posts = await _postService.GetRecentPostsAsync(count);
        return View(posts);
    }
}

Create the View for the ViewComponent (e.g., Views/Shared/Components/RecentPosts/Default.cshtml):

<ul>
    @foreach (var post in Model)
    {
        <li>@post.Title</li>
    }
</ul>

Invoke the ViewComponent from a View:

@await Component.InvokeAsync("RecentPosts", new { count = 5 })

3.In this example, the RecentPostsViewComponent fetches recent posts and passes them to a view for rendering.

30. What are Filters in ASP.NET Core, and how do they work?

Filters in ASP.NET Core are used to execute code before or after certain stages in the request pipeline. They provide a way to inject cross-cutting concerns, such as logging, error handling, or authorization, into your application's action methods.

Types of filters in ASP.NET Core:

  1. Authorization Filters: Run before any other filters to verify whether the user is authorized to access the resource.
  2. Resource Filters: Execute before and after model binding.
  3. Action Filters: Run before and after the execution of the action method.
  4. Exception Filters: Handle any exceptions thrown during the processing of the request.
  5. Result Filters: Run before and after the execution of the action result.

Example of an Action Filter:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Code that runs before the action method
        Console.WriteLine("Action executing: " + context.ActionDescriptor.DisplayName);
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        // Code that runs after the action method
        Console.WriteLine("Action executed");
    }
}

You can apply this filter globally, on a controller, or on an individual action method.

Applying the filter globally:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews(options =>
    {
        options.Filters.Add(new LogActionFilter());
    });
}

Applying the filter to a controller or action:

[LogActionFilter]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Filters allow you to centralize logic that applies across multiple actions or controllers, making your code more modular and maintainable.

Here are the next five intermediate-level .NET Core interview questions and their detailed answers:

31. What is Dependency Injection (DI) in ASP.NET Core, and how is it implemented?

Dependency Injection (DI) is a design pattern used in ASP.NET Core to decouple the instantiation of classes from their dependencies. This enables better maintainability, testing, and flexibility of the application. DI allows objects to declare their dependencies through constructors, and the DI framework takes care of providing the necessary dependencies.

ASP.NET Core provides built-in support for DI, making it easy to implement throughout the application.

How DI works in ASP.NET Core:

Services (dependencies) are registered in the Startup.cs class, usually inside the ConfigureServices method.

Services can be registered with different lifetimes:

  • Singleton: One instance is created and shared throughout the application's lifetime.
  • Scoped: A new instance is created for each HTTP request.
  • Transient: A new instance is created each time it is requested.

Example of configuring DI in ASP.NET Core:

Registering services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMySingletonService, MySingletonService>();
    services.AddScoped<IMyScopedService, MyScopedService>();
    services.AddTransient<IMyTransientService, MyTransientService>();
}

1. Injecting services into a controller:

public class HomeController : Controller
{
    private readonly IMySingletonService _singletonService;
    private readonly IMyScopedService _scopedService;
    private readonly IMyTransientService _transientService;

    public HomeController(IMySingletonService singletonService, 
                          IMyScopedService scopedService, 
                          IMyTransientService transientService)
    {
        _singletonService = singletonService;
        _scopedService = scopedService;
        _transientService = transientService;
    }

    public IActionResult Index()
    {
        // Use the injected services
        return View();
    }
}

2. Benefits of Dependency Injection:

  1. Loose coupling: The dependencies are not tightly bound to the classes.
  2. Improved testability: Dependencies can be easily mocked during unit testing.
  3. Better maintainability: It is easier to modify and extend code without changing class implementations.

DI is a core feature of ASP.NET Core, simplifying application architecture and enhancing flexibility.

32. What is IServiceProvider, and how is it used in ASP.NET Core?

IServiceProvider is the interface used to resolve services (dependencies) that have been registered in the DI container. It is the core part of ASP.NET Core’s dependency injection mechanism. The IServiceProvider is responsible for providing instances of services when they are requested by controllers, middleware, or other components.

How IServiceProvider works:

  • When services are registered in the ConfigureServices method of Startup.cs, they are stored in the service container.
  • The IServiceProvider is used by the framework to resolve services from this container.
  • It can be injected into your classes or used manually when resolving services that are not known at compile time.

Example of manually using IServiceProvider:

public class MyClass
{
    private readonly IServiceProvider _serviceProvider;

    public MyClass(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void UseService()
    {
        var myService = _serviceProvider.GetService<IMyService>();
        // Use the resolved service
    }
}

In this example, IServiceProvider is injected into the class, and the service IMyService is resolved dynamically at runtime.

Common methods of IServiceProvider:

  1. GetService<TService>(): Returns the requested service if registered, or null if it is not.
  2. GetRequiredService<TService>(): Returns the requested service, but throws an exception if the service is not registered.

In most scenarios, you rely on constructor injection for services, but IServiceProvider is useful when you need dynamic or late-bound service resolution.

33. How does logging work in ASP.NET Core?

ASP.NET Core includes built-in support for logging via the Microsoft.Extensions.Logging library. This system allows you to record log messages of varying severity to various outputs, such as the console, files, or third-party services like Azure or Serilog.

Key features of ASP.NET Core logging:

Log levels: Logging supports different severity levels:

  1. Trace
  2. Debug
  3. Information
  4. Warning
  5. Error
  6. Critical

Logging providers: ASP.NET Core includes several logging providers, such as Console, Debug, EventSource, and EventLog. You can also add third-party providers like Serilog or NLog.

How to configure logging:

In appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Information",
      "System": "Error"
    }
  }
}

In Startup.cs:

public void Configure
(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    logger.LogInformation("Application is starting");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        logger.LogDebug("In development mode");
    }
}

In this example, logging levels are defined in appsettings.json, and the ILogger is injected into the Startup.cs class for use.

Injecting the ILogger in a controller:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Home page accessed.");
        return View();
    }
}

Adding third-party logging providers (e.g., Serilog):

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog((context, configuration) =>
        {
            configuration
                .WriteTo.Console()
                .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Logging in ASP.NET Core is flexible, allowing developers to capture useful information during development and in production for debugging and auditing purposes.

34. What is IConfiguration in ASP.NET Core, and how does it help in managing settings?

IConfiguration is an interface in ASP.NET Core used to access configuration settings from various sources like JSON files, environment variables, command-line arguments, and user secrets. It is part of the Microsoft.Extensions.Configuration namespace and provides a unified way to handle configurations in the application.

Key features of IConfiguration:

  • Supports hierarchical key-value pairs.
  • Allows configurations to be loaded from multiple sources and merged.
  • Supports strongly-typed configuration models.

Common configuration sources:

  1. appsettings.json and environment-specific JSON files (like appsettings.Development.json).
  2. Environment variables.
  3. Command-line arguments.
  4. User secrets (for storing sensitive data during development).

How IConfiguration works:

In Startup.cs, it is injected into the constructor:

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var mySetting = _configuration["MySettingKey"];
    }
}

1. Accessing nested settings:

var connectionString = _configuration["ConnectionStrings:DefaultConnection"];

2. Example of binding configuration to a strongly-typed model:

public class MySettings
{
    public string ApiKey { get; set; }
    public string ApiUrl { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MySettings>(_configuration.GetSection("MySettings"));
}

Reading environment variables:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServer;Database=myDB;"
  }
}

The IConfiguration interface in ASP.NET Core makes it easy to manage settings in a flexible, environment-friendly way, allowing developers to centralize and configure application settings without hardcoding them.

35. What is the IOptions<T> pattern in ASP.NET Core?

The IOptions<T> pattern in ASP.NET Core is used to access strongly-typed configuration settings. It allows you to bind configuration sections from appsettings.json or other sources directly to C# classes, making it easier to manage and access configuration values throughout the application.

How IOptions<T> works:

  1. **Define a class that represents the configuration
  2. Bind the configuration section to the class using the Configure<T> method.
  3. Access the configuration values through dependency injection.

Example:

Create a settings class:

public class MySettings
{
    public string ApiUrl { get; set; }
    public string ApiKey { get; set; }
}

1.Configure the settings in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MySettings>(_configuration.GetSection("MySettings"));
}

2. Access the settings using IOptions<T> in a controller:

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        var apiUrl = _mySettings.ApiUrl;
        var apiKey = _mySettings.ApiKey;
        return View();
    }
}

IOptionsSnapshot<T> and IOptionsMonitor<T> are advanced variations that allow for runtime updates of configuration settings.The IOptions<T> pattern helps maintain clean and organized code by separating configuration management into its own class, simplifying access to application settings.

36. What is Middleware in ASP.NET Core, and how do you create custom Middleware?

In ASP.NET Core, Middleware is a component that processes HTTP requests and responses in a pipeline. Each middleware component can:

  • Handle the request (e.g., authentication, routing).
  • Pass the request to the next middleware in the pipeline.
  • Modify the response.

The request flows through the middleware pipeline, and each component can modify the request or response at various stages.How Middleware works:

  1. The middleware pipeline is configured in the Startup.cs file inside the Configure method.
  2. The order in which middleware is added is important because each middleware component can influence the next.
  3. Common built-in middleware includes authentication, routing, static files, and exception handling.

Example of the middleware pipeline:

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

Creating custom middleware:

To create custom middleware, you can define a class that processes the request and calls the next middleware in the pipeline.

Steps:

  1. Create a middleware class.
  2. Implement a method called InvokeAsync that takes HttpContext and RequestDelegate.
  3. Register the middleware in the pipeline.

Example of custom middleware:

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Custom logic before the next middleware
        Console.WriteLine("Before Request");

        // Call the next middleware in the pipeline
        await _next(context);

        // Custom logic after the next middleware
        Console.WriteLine("After Request");
    }
}

Register custom middleware in Startup.cs:

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<CustomMiddleware>();
    app.UseRouting();
}

Middleware is a fundamental concept in ASP.NET Core, allowing for modular and reusable components that process HTTP requests.

37. How does session management work in ASP.NET Core?

In ASP.NET Core, session management is used to store temporary data specific to a user across multiple HTTP requests. Unlike cookies, session data is stored server-side, and a session ID is passed to the client via a cookie.

How session management works:

  1. Session data is stored in the server's memory, a distributed cache, or a database.
  2. The session ID is stored in a cookie on the client.
  3. Each time the user makes a request, the session ID is sent with the request, and the server retrieves the corresponding session data.

Configuring session management:

Add the required session services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache(); // Required for session
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(30);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
}

1. Use session middleware in the request pipeline:

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
}

2. Store and retrieve session data in a controller:

public IActionResult Index()
{
    HttpContext.Session.SetString("Username", "JohnDoe");
    string username = HttpContext.Session.GetString("Username");

    return View();
}

3. Session storage options:

  • In-memory (default): Stores session data in memory (useful for development).
  • Distributed cache: Stores session data in a distributed cache like Redis or SQL Server.

Session management in ASP.NET Core is useful for maintaining user-specific data across multiple requests in a secure and scalable way.

38. What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()?

Both Use() and Run() are used to add middleware components to the ASP.NET Core middleware pipeline, but they serve different purposes:

IApplicationBuilder.Use():

  1. Adds middleware that can pass the request to the next middleware in the pipeline.
  2. It calls the next middleware by invoking next() within its delegate.
  3. Middleware registered with Use() can modify both the incoming request and outgoing response.

Example of Use():

app.Use(async (context, next) =>
{
    // Logic before the next middleware
    Console.WriteLine("Before next middleware");

    await next(); // Call the next middleware

    // Logic after the next middleware
    Console.WriteLine("After next middleware");
});

IApplicationBuilder.Run():

  1. Terminates the request processing pipeline.
  2. It does not call the next middleware. Once Run() is called, no other middleware is invoked after it.
  3. Typically used for middleware that should handle the request completely (e.g., error handling, static files).

Example of Run():

app.Run(async context =>
{
    await context.Response.WriteAsync("Request handled completely");
});

Key difference:

  • Use() calls the next middleware in the pipeline, while Run() stops the pipeline from continuing.
  • You can chain multiple Use() calls, but Run() usually appears last, as it terminates the pipeline.

39. What is UseEndpoints() in ASP.NET Core, and how does it differ from UseMvc()?

UseEndpoints() and UseMvc() are methods in ASP.NET Core used to configure request handling, but they differ in how they manage routing and endpoints.

UseMvc():

  1. Part of the older routing system in ASP.NET Core 2.x.
  2. Configures routing based on controller actions, with routes defined explicitly in Startup.cs or using attribute-based routing.
  3. It was commonly used with services.AddMvc() in the ConfigureServices() method.

Example:

public void Configure(IApplicationBuilder app)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

UseEndpoints():

  1. Introduced in ASP.NET Core 3.x as part of the endpoint routing system.
  2. Allows for routing based on different endpoints, such as MVC controllers, Razor pages, gRPC services, and SignalR hubs, in a more unified way.
  3. Typically used with services.AddControllers(), services.AddRazorPages(), etc.

Example:

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

Key difference:

  • UseMvc() is tied to the older non-endpoint routing system.
  • UseEndpoints() is part of the modern endpoint routing system, allowing greater flexibility in how routing is handled for multiple types of requests.

Endpoint routing is the recommended approach in ASP.NET Core 3.x and later, as it simplifies and unifies routing across different types of requests (MVC, Razor Pages, SignalR, etc.).

40. How do you implement exception handling in ASP.NET Core?

In ASP.NET Core, exception handling can be managed using middleware that catches unhandled exceptions and returns appropriate responses, typically through custom error pages or JSON responses for API endpoints.Key techniques for exception handling:

Developer Exception Page (for development environments):

  1. Shows detailed exception information during development.
  2. Use this only in a development environment.

Example:

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

Exception Handling Middleware (for production environments):

  1. Catches exceptions globally and allows you to show custom error pages or responses.
  2. Typically used in production environments.

Example:

public void Configure(IApplicationBuilder app)
{
    app.UseExceptionHandler("/Home/Error"); // Custom error page for exceptions
}

Custom Exception Handling Middleware:

  1. You can create your own middleware to handle exceptions in a more customized way, such as returning JSON for APIs or logging errors.

Example of custom exception handling middleware:

public class CustomExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public CustomExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            // Handle exception
            context.Response.StatusCode = 500;
            await context.Response.WriteAsync("An error occurred.");
        }
    }
}

// Register the middleware in Startup.cs
public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<CustomExceptionMiddleware>();
}

Logging exceptions:

  • ASP.NET Core integrates with logging frameworks to log exceptions in production environments using providers like Serilog, NLog, or the built-in logging system.

By setting up proper exception handling middleware, you can ensure that unhandled exceptions are captured, logged, and returned in a user-friendly way based on the application type (MVC, API, etc.).

.Net Core Interview Questions & Answers For Experienced

1. What is the CQRS (Command Query Responsibility Segregation) pattern, and how do you implement it in .NET Core?

CQRS Pattern: CQRS is a pattern that separates read and write operations into different models. The idea is to allow for optimization of both sides independently, making the system more scalable and maintainable.

Implementation in .NET Core:

  • Define Commands and Queries: Create separate classes for commands (write operations) and queries (read operations).
  • Use Command Handlers: Implement command handlers that process the commands. Use the IRequestHandler<TRequest, TResponse> interface from the MediatR library.
  • Use Query Handlers: Similarly, create query handlers for handling queries.
  • Set Up Repositories: Use repositories to interact with the database. You can have different databases for reading and writing.
  • Service Layer: Create a service layer that interacts with command and query handlers.

Example:

public class CreateProductCommand : IRequest<Product>
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class CreateProductCommandHandler : IRequestHandler
<CreateProductCommand, Product>
{
    public async Task<Product> Handle
    (CreateProductCommand request, CancellationToken cancellationToken)
    {
        // Logic to create a product
    }
}

// Query
public class GetProductQuery : IRequest<Product>
{
    public int Id { get; set; }
}

public class GetProductQueryHandler : IRequestHandler
<GetProductQuery, Product>
{
    public async Task<Product> Handle
    (GetProductQuery request, CancellationToken cancellationToken)
    {
        // Logic to get a product by ID
    }
}

2. How do you handle distributed transactions in a microservice architecture using .NET Core?

Handling Distributed Transactions: In microservice architecture, handling distributed transactions can be complex. Here are some approaches:

  • Two-Phase Commit (2PC): While this is a traditional approach, it can lead to tight coupling between services, making it less favorable.
  • Saga Pattern: This is a more common approach. It consists of a series of local transactions where each transaction updates a service and publishes an event or message to trigger the next transaction.
  • Compensating Transactions: If a step fails, the previous steps must be undone, often using compensating transactions.
  • Eventual Consistency: Accept that not all operations are completed in one transaction. Instead, rely on asynchronous messaging to eventually synchronize states across services.

3. How do you implement the Event Sourcing pattern in .NET Core?

Event Sourcing Pattern: Event sourcing stores the state of a system as a sequence of events. Instead of storing just the current state, you store every change that has occurred.

Implementation Steps:

  • Define Events: Create event classes that represent the changes in the system.
  • Event Store: Use an event store to save events. This could be a database or a message queue.
  • Aggregate Roots: Use aggregate roots to handle the business logic and ensure that all changes are consistent.
  • Replay Events: To rebuild the current state, replay the events from the event store.

Example:

public class ProductCreatedEvent
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Store events in a database
public void SaveEvent(Event @event)
{
    // Logic to save the event
}

// Replay events to get the current state
public Product GetProductById(int id)
{
    var events = _eventStore.GetEventsForAggregate(id);
    // Logic to replay events
}

4. Explain the Saga pattern for handling distributed transactions in .NET Core microservices.

Saga Pattern: The Saga pattern is a way to manage distributed transactions by breaking them down into a series of smaller, manageable transactions that can be completed independently. It can be implemented in two ways:

  • Choreography: Each service produces and listens for events. The services are loosely coupled and can operate independently.
  • Orchestration: A central orchestrator service directs the flow of the saga, coordinating the various services.

Implementation Steps:

  1. Define the Saga: Identify the sequence of operations that need to be completed.
  2. Implement Choreography: Each service publishes events when it completes its operation, triggering the next service in the saga.
  3. Implement Orchestration: Use a saga orchestrator that manages the flow and calls each service in the correct order.
  4. Compensating Transactions: Define compensating actions for each step in case a step fails.

5. How do you integrate .NET Core with Docker, and what are the benefits?

Integrating .NET Core with Docker:

  • Dockerfile: Create a Dockerfile in your .NET Core project that defines how to build your application in a Docker container.

Example Dockerfile:

# Use the official .NET SDK image
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o out

# Use the official .NET runtime image
FROM mcr.microsoft.com/dotnet/aspnet:7.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "YourApp.dll"]
  • Docker Compose: Use Docker Compose to define and run multi-container Docker applications.

Benefits of Using Docker:

  • Environment Consistency: Ensures that applications run the same way in development, testing, and production.
  • Isolation: Each service runs in its own container, isolating dependencies and configurations.
  • Scalability: Easier to scale services independently.
  • Portability: Docker containers can run on any system that supports Docker, making deployments easier.

6. How do you handle logging in microservices using centralized logging in .NET Core?

Centralized Logging: Centralized logging collects logs from various microservices into a single location, facilitating monitoring and analysis.Implementation Steps:

  1. Choose a Logging Framework: Use frameworks like Serilog, NLog, or log4net that support structured logging.
  2. Centralized Log Storage: Use solutions like ELK Stack (Elasticsearch, Logstash, Kibana), Azure Application Insights, or Splunk.
  3. Structured Logging: Log data in a structured format (e.g., JSON) to make querying and analysis easier.
  4. Configure Logging: Update appsettings.json to configure logging.

Example using Serilog:

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.Console()
            .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
            {
                AutoRegisterTemplate = true
            })
            .CreateLogger();

        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog() // Using Serilog for logging
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

7. How do you implement Polly for handling transient faults in .NET Core applications?

Polly Overview: Polly is a resilience library for .NET that helps manage transient faults by implementing policies such as retries, circuit breakers, and timeouts.

Implementation Steps:

  1. Install Polly: Add the Polly NuGet package to your project.
  2. Define Resilience Policies: Create policies for retry, circuit breaker, etc.
  3. Wrap HTTP Calls: Use the defined policies around HTTP calls to external services.

Example of a Retry Policy:

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .RetryAsync(3); // Retries 3 times

await retryPolicy.ExecuteAsync(async () =>
{
    // Your HTTP call
});

8. How do you integrate gRPC in a .NET Core application for inter-service communication?

gRPC Integration Steps:

  1. Add gRPC Packages: Include Grpc.AspNetCore and Google.Protobuf packages.
  2. Define Protos: Create .proto files to define service methods and messages.
  3. Generate Code: Use the Protobuf compiler to generate C# code from .proto files.
  4. Configure Services in Startup: Register gRPC services in the Startup.cs.

Example Proto File:

// product.proto
syntax = "proto3";

service ProductService {
    rpc GetProduct (ProductRequest) returns (ProductResponse);
}

message ProductRequest {
    int32 id = 1;
}

message ProductResponse {
    string name = 1;
    double price = 2;
}

Startup Configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc(); // Add gRPC services
}

// In the Configure method
app.UseEndpoints(endpoints =>
{
    endpoints.MapGrpcService<ProductService>(); // Map the gRPC service
});

9. What are the best practices for optimizing performance in high-traffic .NET Core applications?

Performance Optimization Best Practices:

  1. Asynchronous Programming: Utilize async/await to prevent blocking threads.
  2. Caching: Implement caching strategies (in-memory, distributed) to reduce repetitive database calls.
  3. Load Balancing: Use load balancers to evenly distribute traffic among instances.
  4. Efficient Database Access: Optimize queries and use appropriate indexing.
  5. Connection Pooling: Use connection pooling for efficient database connections.
  6. Minimize Middleware: Limit the use of middleware to essential components.
  7. Response Compression: Enable gzip compression to reduce the size of responses.

10. How do you implement Circuit Breaker and Retry patterns using Polly in .NET Core?

Circuit Breaker and Retry Patterns: You can create a combined policy using Polly for circuit breaking and retries.

Example Implementation:

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .RetryAsync(3); // Retry 3 times

var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync
    (2, TimeSpan.FromMinutes(1)); // Break after 2 failures for 1 minute

var combinedPolicy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);

await combinedPolicy.ExecuteAsync(async () =>
{
    // Your HTTP call here
});

11. How do you manage caching at scale for distributed applications in .NET Core?

Managing Caching at Scale:

  1. Distributed Caching: Use Redis or Memcached for distributed caching to share data across instances.
  2. Cache Invalidation: Implement strategies for cache invalidation to ensure data consistency.
  3. Partitioning Data: Partition data across multiple cache nodes to balance load.
  4. Expiration Policies: Set appropriate expiration for cached items to manage memory usage efficiently.

Example using Redis:

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

12. How do you deploy a .NET Core application to a Kubernetes cluster?

Deployment Steps:

  1. Create Docker Image: Build a Docker image for your .NET Core application.
  2. Define Kubernetes Configuration Files: Create YAML files for your deployment and service specifications.
  3. Deploy Using kubectl: Use kubectl commands to deploy your application to the Kubernetes cluster.

Example YAML for Deployment and Service:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-dotnet-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-dotnet-app
  template:
    metadata:
      labels:
        app: my-dotnet-app
    spec:
      containers:
      - name: my-dotnet-app
        image: my-dotnet-app:latest
        ports:
        - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: my-dotnet-app
spec:
  selector:
    app: my-dotnet-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer

13. How do you handle API versioning in an ASP.NET Core Web API?

API Versioning Implementation:

  1. Install API Versioning Package: Add Microsoft.AspNetCore.Mvc.Versioning NuGet package.
  2. Configure Versioning in Startup: Set up API versioning options in Startup.cs.

Example:

services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
});

// Define versioned controllers
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase
{
    // Actions for version 1.0
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase
{
    // Actions for version 2.0
}

14. How do you integrate OAuth2 and OpenID Connect in a .NET Core application?

OAuth2 and OpenID Connect Integration:

  1. Install Required NuGet Packages: Use Microsoft.AspNetCore.Authentication.JwtBearer and Microsoft.AspNetCore.Authentication.OpenIdConnect.
  2. Configure Authentication in Startup: Set up the authentication middleware to validate incoming tokens.

Example:

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = "https://your-auth-server";
    options.Audience = "your-api-audience";
});

app.UseAuthentication(); // Enable authentication middleware

15. How do you implement hybrid transactions across microservices in .NET Core?

Hybrid Transactions Handling: Hybrid transactions can be complex and may involve several strategies:

  • Transaction Coordinator: Implement a transaction coordinator to manage transactions across services.
  • Saga Pattern: Use the Saga pattern to decompose the process into local transactions that can be compensated.
  • Event-Driven Architecture: Employ events to trigger processes and maintain state across services.

16. How do you secure microservices using JWT and Identity Server in .NET Core?

Microservices Security:

  1. Use Identity Server: Set up Identity Server for authentication and issuing JWT tokens.
  2. JWT Bearer Authentication: Configure your microservices to validate JWT tokens.

Example Configuration:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://your-identity-server";
        options.Audience = "your-api-audience";
    });

17. What is GraphQL, and how do you implement it in .NET Core?

GraphQL Overview: GraphQL is a query language for APIs that allows clients to request only the data they need.

Implementation Steps:

  1. Install GraphQL NuGet Packages: Add GraphQL and GraphQL.Server packages.
  2. Define GraphQL Schema: Create a schema that defines types, queries, and mutations.
  3. Configure GraphQL in Startup: Register GraphQL services in Startup.cs.

Example:

services.AddGraphQLServer()
    .AddQueryType<Query>() // Define your Query class
    .AddMutationType<Mutation>(); // Define your Mutation class

18. How do you scale an ASP.NET Core application using Azure Kubernetes Service (AKS)?

Scaling with AKS:

  1. Deploy to AKS: Use Kubernetes to deploy your ASP.NET Core application.
  2. Horizontal Pod Autoscaler: Implement HPA to automatically scale the number of pods based on CPU usage or custom metrics.
  3. Load Balancing: Use Azure Load Balancer to distribute traffic across instances.

Example HPA Configuration:

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: my-dotnet-app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-dotnet-app
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70

19. How do you handle message-driven microservices using RabbitMQ in .NET Core?

Message-Driven Microservices:

  1. Install RabbitMQ Client: Add the RabbitMQ.Client NuGet package.
  2. Configure RabbitMQ Connection: Set up a connection to your RabbitMQ server in your application.
  3. Publish and Consume Messages: Use RabbitMQ to publish messages and create consumers for processing them.

Example Publisher:

using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
    channel.QueueDeclare
    (queue: "queue_name", durable: false, exclusive: false, autoDelete: false, arguments: null);
    
    var body = Encoding.UTF8.GetBytes("Hello World");
    channel.BasicPublish(exchange: "", routingKey: "queue_name", basicProperties: null, body: body);
}

20. How do you implement distributed tracing in a .NET Core microservice architecture?

Distributed Tracing: Distributed tracing helps track requests across microservices.

Implementation Steps:

  1. Use OpenTelemetry: Integrate OpenTelemetry SDK to capture traces.
  2. Instrumentation: Instrument your application to create spans and add context to traces.
  3. Export Traces: Send traces to a backend like Jaeger, Zipkin, or Azure Monitor for visualization.

Example Configuration:

services.AddOpenTelemetryTracing(builder =>
{
    builder.AddAspNetCoreInstrumentation()
           .AddHttpClientInstrumentation()
           .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("YourServiceName"))
           .AddJaegerExporter();
});

21. How do you implement zero-downtime deployments for .NET Core applications in production?

Zero-Downtime Deployment Strategies:

  1. Blue-Green Deployment: Maintain two identical environments (blue and green). Deploy the new version to the inactive environment and switch traffic when ready.
  2. Rolling Deployment: Gradually replace instances of the old version with the new version, ensuring that some instances of the old version are always running.
  3. Canary Release: Release the new version to a small subset of users before rolling it out to the entire user base. Monitor performance and rollback if issues arise.
  4. Load Balancer Configuration: Use a load balancer to manage traffic to both versions during the deployment process.

Example Steps:

  • Use a CI/CD pipeline to automate deployments.
  • Use Docker for containerization to ensure consistent environments.
  • Utilize Kubernetes for managing rolling updates and scaling.

22. How do you work with Azure Functions in a .NET Core application?

Working with Azure Functions:

  1. Create a Function App: Use the Azure portal or Azure CLI to create a new Function App.
  2. Choose Trigger Type: Select triggers like HTTP, Timer, or Queue.
  3. Write Function Code: Implement the logic in the function's code file.

Example HTTP Trigger Function:

[FunctionName("HttpTriggerFunction")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    return new OkObjectResult("Hello, Azure Functions!");
}
  1. Deploy and Test: Deploy the function using Azure DevOps or directly from Visual Studio.

23. How do you handle large file uploads and downloads in a .NET Core Web API?

Handling Large Files:

  1. Configure Kestrel Server: Increase limits for request body size in Startup.cs.
  2. Use Streamed File Uploads: Accept file streams to minimize memory usage.

Example Configuration:

services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
});

File Upload Example:

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    if (file.Length > 0)
    {
        var path = Path.Combine("uploads", file.FileName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        return Ok();
    }
    return BadRequest();
}

File Download Example:

[HttpGet("download/{fileName}")]
public IActionResult Download(string fileName)
{
    var path = Path.Combine("uploads", fileName);
    var fileStream = new FileStream(path, FileMode.Open);
    return File(fileStream, "application/octet-stream", fileName);
}

24. What are the different strategies for scaling out microservices in .NET Core?

Scaling Strategies:

  1. Horizontal Scaling: Add more instances of microservices to handle increased load.
  2. Load Balancing: Distribute incoming requests evenly across instances using load balancers.
  3. Service Mesh: Use a service mesh like Istio to manage service-to-service communication and traffic routing.
  4. Auto-scaling: Implement auto-scaling policies based on CPU usage, memory, or custom metrics in Kubernetes.

25. How do you optimize SQL queries using Dapper in .NET Core?

Optimizing SQL Queries with Dapper:

  1. Use Parameterized Queries: Prevent SQL injection and improve performance.
  2. Select Only Necessary Fields: Fetch only required columns instead of using SELECT *.
  3. Use Asynchronous Methods: Utilize Dapper's async methods for database calls.

Example Query:

using (var connection = new SqlConnection(connectionString))
{
    var sql = "SELECT Id, Name FROM Products WHERE CategoryId = @CategoryId";
    var products = await connection.QueryAsync<Product>(sql, new { CategoryId = 1 });
}

26. How do you handle concurrency conflicts in a multi-user Entity Framework Core application?

Concurrency Handling:

  1. Optimistic Concurrency: Use a concurrency token (e.g., timestamp) in your model.
  2. Catch DbUpdateConcurrencyException: Handle exceptions when saving changes to resolve conflicts.

Example Model Configuration:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    [Timestamp]
    public byte[] RowVersion { get; set; } // Concurrency token
}

Handling Concurrency Exception:

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    // Handle conflict (e.g., notify user, reload entity, etc.)
}

27. How do you implement a global exception handler for microservices in .NET Core?

Global Exception Handling:

  1. Middleware: Create custom middleware to handle exceptions globally.
  2. Logging: Log exceptions for monitoring and debugging.

Example 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)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return context.Response.WriteAsync("An unexpected error occurred.");
    }
}

Register Middleware in Startup:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<ExceptionHandlingMiddleware>();
    // Other middleware registrations...
}

28. How do you implement authentication using Active Directory and Azure AD in .NET Core?

Authentication Steps:

  1. Register Application: Register your app in the Azure portal to use Azure AD.
  2. Install NuGet Packages: Add Microsoft.AspNetCore.Authentication.AzureAD.UI for Azure AD authentication.
  3. Configure Authentication in Startup: Set up authentication options in Startup.cs.

Example Configuration:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));

app.UseAuthentication(); // Enable authentication middleware

29. How do you secure a .NET Core application with HTTPS and certificates?

Securing with HTTPS:

  1. Use Kestrel: Configure Kestrel to use HTTPS with a certificate.
  2. Redirect HTTP to HTTPS: Force HTTPS by redirecting all HTTP traffic.

Example Kestrel Configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpsRedirection(options =>
    {
        options.HttpsPort = 443; // Redirect to this port
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseHttpsRedirection();
    // Other middleware...
}

30. How do you integrate ElasticSearch with .NET Core for full-text search capabilities?

Integrating ElasticSearch:

  1. Install ElasticSearch Client: Use Elasticsearch.Net and NEST packages for .NET Core.
  2. Configure ElasticSearch Connection: Set up connection details in Startup.cs.

Example Configuration:

services.AddSingleton<IElasticClient>
(new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200"))));

Example Search Query:

var searchResponse = await elasticClient.SearchAsync<Product>(s => s
    .Index("products")
    .Query(q => q
        .Match(m => m
            .Field(f => f.Name)
            .Query("search term")
        )
    )
);

31. How do you implement API Gateway in a microservices architecture with .NET Core?

API Gateway Overview: An API Gateway acts as a single entry point for microservices, handling requests, routing, and aggregation.

Implementation Steps:

  1. Use Ocelot: A popular .NET Core library for building API gateways.
  2. Configure Ocelot: Set up routes and services in ocelot.json.

Example ocelot.json:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/products",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/products",
      "UpstreamHttpMethod": [ "GET" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000"
  }
}

Startup Configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOcelot(); // Add Ocelot services
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers(); // Map controllers
    });

    app.UseOcelot().Wait(); // Use Ocelot middleware
}

32. What is Orleans, and how do you use it in .NET Core for distributed systems?

Overview of Orleans: Orleans is a framework for building distributed applications, leveraging virtual actors for scalability and fault tolerance.

Implementation Steps:

  1. Install Orleans Packages: Add Microsoft.Orleans.Server and related packages.
  2. Configure Orleans in Startup: Set up Orleans host and configure grain services.

Example Configuration:

services.AddOrleansClient(clientBuilder =>
{
    clientBuilder.UseLocalhostClustering();
});

Example Grain Interface:

public interface IMyGrain : IGrainWithStringKey
{
    Task<string> GetGreeting(string name);
}

Implement Grain:

public class MyGrain : Grain, IMyGrain
{
    public Task<string> GetGreeting(string name)
    {
        return Task.FromResult($"Hello, {name}!");
    }
}

33. How do you implement JWT refresh tokens securely in a .NET Core Web API?

JWT Refresh Tokens:

  1. Generate Refresh Tokens: Issue a refresh token alongside the access token upon authentication.
  2. Store Refresh Tokens: Store them securely (e.g., in a database or a secure store).

Example Token Generation:

var refreshToken = GenerateRefreshToken();
await SaveRefreshTokenToDatabase(user.Id, refreshToken);

Token Refresh Endpoint:

[HttpPost("refresh-token")]
public async Task<IActionResult> RefreshToken(string token)
{
    var principal = ValidateToken(token);
    if (principal == null) return Unauthorized();
    
    var newToken = GenerateAccessToken(principal);
    return Ok(new { AccessToken = newToken });
}

34. How do you optimize memory management and garbage collection in .NET Core for high-performance applications?

Memory Management Optimization:

  1. Use Structs Over Classes: Use value types (structs) for small data structures to reduce heap allocations.
  2. Minimize Allocations: Use object pooling to reuse instances of expensive objects.
  3. Avoid Large Object Heap: Break large objects into smaller ones if possible to avoid fragmentation.

Profiling Tools: Utilize tools like the .NET Memory Profiler or Visual Studio's Diagnostic Tools to analyze memory usage.

35. How do you handle multitenancy in an ASP.NET Core application?

Multitenancy Approaches:

  1. Database-per-Tenant: Each tenant has its own database, offering complete isolation.
  2. Shared Database with Tenant ID: Use a single database and add a Tenant ID column to tables to filter data.
  3. Hybrid Approach: Use a combination of the above methods based on tenant needs.

Example Shared Database Model:

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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int TenantId { get; set; } // Multitenancy key
}

36. How do you configure load balancing for .NET Core applications running on Kubernetes?

Load Balancing in Kubernetes:

  1. Use Kubernetes Services: Create a service of type LoadBalancer or ClusterIP.
  2. Ingress Controller: Use an Ingress controller to manage external access to services.

Example Service Configuration:

apiVersion: v1
kind: Service
metadata:
  name: my-dotnet-app
spec:
  type: LoadBalancer
  ports:
    - port: 80
      targetPort: 5000
  selector:
    app: my-dotnet-app

37. How do you monitor performance and health in a production .NET Core application?

Monitoring Techniques:

  1. Application Insights: Use Azure Application Insights for telemetry, performance metrics, and logging.
  2. Health Checks: Implement health checks using the Microsoft.AspNetCore.Diagnostics.HealthChecks package.

Example Health Check Configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks();
}

public void Configure(IApplicationBuilder app)
{
    app.UseHealthChecks("/health");
}

38. How do you implement WebSockets for real-time communication in ASP.NET Core?

Implementing WebSockets:

  1. Add WebSocket Middleware: Configure WebSocket support in Startup.cs.
  2. Create WebSocket Handler: Write logic for handling WebSocket connections.

Example Configuration:

public void Configure(IApplicationBuilder app)
{
    app.UseWebSockets();
    app.Use(async (context, next) =>
    {
        if (context.WebSockets.IsWebSocketRequest)
        {
            using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
            await HandleWebSocketAsync(webSocket);
        }
        else
        {
            await next();
        }
    });
}

WebSocket Handler Example:

private async Task HandleWebSocketAsync(WebSocket webSocket)
{
    var buffer = new byte[1024 * 4];
    WebSocketReceiveResult result;

    do
    {
        result = await webSocket.ReceiveAsync
        (new ArraySegment<byte>(buffer), CancellationToken.None);
        // Handle received messages...
    } while (!result.CloseStatus.HasValue);

    await webSocket.CloseAsync
    (result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}

39. How do you integrate message queues like Azure Service Bus in a .NET Core application?

Integrating Azure Service Bus:

  1. Install NuGet Package: Add Microsoft.Azure.ServiceBus.
  2. Configure Service Bus Client: Set up connection strings and queues.

Example Configuration:

var connectionString = "YourConnectionString";
var queueClient = new QueueClient(connectionString, "YourQueueName");

Sending Messages Example:

var message = new Message
(Encoding.UTF8.GetBytes("Hello, Azure Service Bus!"));
await queueClient.SendAsync(message);

Receiving Messages Example:

var messageHandlerOptions = new MessageHandlerOptions
(ExceptionReceivedHandler)
{
    MaxConcurrentCalls = 1,
    AutoComplete = false
};

queueClient.RegisterMessageHandler
(ProcessMessagesAsync, messageHandlerOptions);

40. How do you architect a microservice-based solution using .NET Core for cloud-native applications?

Architecting Microservices:

  1. Identify Microservices: Break down the application into smaller services based on business capabilities.
  2. Design APIs: Define RESTful APIs or use gRPC for communication between services.
  3. Database Strategy: Choose appropriate database strategies (e.g., polyglot persistence).
  4. Infrastructure: Use Docker containers and orchestrate with Kubernetes for deployment.
  5. Monitoring and Logging: Implement centralized logging and monitoring tools for observability.

Example Architecture Diagram: Create an architecture diagram that shows microservices, API gateways, databases, and message queues.

WeCP Team
Team @WeCP
WeCP is a leading talent assessment platform that helps companies streamline their recruitment and L&D process by evaluating candidates' skills through tailored assessments