.NET Interview Questions and Answers - IndianTechnoEra
Latest update Android YouTube

.NET Interview Questions and Answers

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

.NET Core is a cross-platform, open-source, high-performance framework developed by Microsoft for building modern applications. It supports Windows, Linux, and macOS.

.NET Core Features:

  • Cross-platform support
  • Open source
  • High performance
  • Cloud-friendly
  • Microservices support
  • Container support

Difference Between .NET Core and .NET Framework:

.NET Core .NET Framework
Cross-platform Windows only
Open source Limited open source
Better performance Older architecture
Suitable for cloud and microservices Mainly enterprise desktop/web apps

2. How do you create a new Web API project in .NET Core?

Using Visual Studio:

  1. Open Visual Studio
  2. Click Create New Project
  3. Select ASP.NET Core Web API
  4. Choose .NET version
  5. Enable OpenAPI/Swagger
  6. Click Create

Using CLI:

    dotnet new webapi -n MyApi
    cd MyApi
    dotnet run
    

3. What are middleware components in .NET Core?

Middleware components are software components that are assembled into the application's request pipeline. Each middleware handles HTTP requests and responses.

Common Middleware:

  • Authentication Middleware
  • Authorization Middleware
  • Exception Handling Middleware
  • Routing Middleware
  • CORS Middleware
  • Swagger Middleware

Example:

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

4. What is Dependency Injection and how is it built into .NET Core?

Dependency Injection (DI) is a design pattern used to achieve loose coupling between classes. .NET Core provides built-in support for DI.

Service Lifetimes:

  • Transient - New instance every time
  • Scoped - One instance per request
  • Singleton - Single instance throughout application lifetime

Example:

    builder.Services.AddScoped();
    

5. How do you configure appsettings.json in .NET Core?

appsettings.json stores configuration values such as connection strings, API keys, and application settings.

Example appsettings.json:

    {
        "ConnectionStrings": {
            "DefaultConnection": "Server=.;Database=TestDb;Trusted_Connection=True;"
        }
    }
    

Reading Values:

    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    

6. What is the difference between IActionResult and ActionResult<T> in controllers?

IActionResult:

Used when an action method can return multiple response types.

    public IActionResult Get()
    {
        return Ok();
    }
    

ActionResult<T>:

Used when returning strongly typed data.

    public ActionResult<Employee> GetEmployee()
    {
        return employee;
    }
    

7. How do you enable Swagger in a .NET Core Web API?

Install Package:

    Swashbuckle.AspNetCore
    

Program.cs Configuration:

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    app.UseSwagger();
    app.UseSwaggerUI();
    

Swagger provides interactive API documentation and API testing support.


8. Explain the difference between transient, scoped, and singleton lifetimes in dependency injection.

Lifetime Description
Transient Creates a new instance every time requested
Scoped One instance per HTTP request
Singleton Single instance for the entire application

9. How do you implement logging in .NET Core applications?

.NET Core provides built-in logging support through ILogger.

Example:

    private readonly ILogger<EmployeeController> _logger;

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

    _logger.LogInformation("Employee created successfully");
    

Log Levels:

  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Critical

10. What are filters in ASP.NET Core MVC, and when would you use them?

Filters allow code execution before or after specific stages in the MVC pipeline.

Types of Filters:

  • Authorization Filters
  • Action Filters
  • Exception Filters
  • Result Filters
  • Resource Filters

Example:

    public class CustomActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
        }
    }
    

11. How do you implement global exception handling in .NET Core?

Using Middleware:

    app.UseExceptionHandler("/Error");
    

Custom Middleware Example:

    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch(Exception ex)
            {
            }
        }
    }
    

12. What is the purpose of Startup.cs or Program.cs in .NET 6+?

Startup.cs and Program.cs are used to configure services and middleware. In .NET 6+, minimal hosting model mainly uses Program.cs.

Responsibilities:

  • Configure Services
  • Configure Middleware
  • Application Startup Configuration
  • Dependency Injection Registration

13. How do you implement authentication and authorization in .NET Core APIs?

Authentication:

Authentication verifies user identity.

Authorization:

Authorization checks user permissions.

JWT Authentication Example:

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
        });
    

Authorize Attribute:

    [Authorize]
    public class EmployeeController : ControllerBase
    {
    }
    

14. Explain the difference between Kestrel and IIS in hosting .NET Core apps.

Kestrel IIS
Cross-platform web server Windows web server
Built into ASP.NET Core Acts as reverse proxy
Lightweight and fast Advanced hosting features

15. How do you configure health checks in .NET Core microservices?

Configuration:

    builder.Services.AddHealthChecks();

    app.MapHealthChecks("/health");
    

Health checks monitor application health and dependencies.


16. Explain the Circuit Breaker and Retry patterns in resilient APIs.

Retry Pattern:

Automatically retries failed operations.

Circuit Breaker Pattern:

Prevents continuous requests to failing services.

Polly Example:

    builder.Services.AddHttpClient("api")
        .AddTransientHttpErrorPolicy(policy =>
            policy.RetryAsync(3));
    

17. How does the IHostedService interface work, and when would you use it?

IHostedService is used for background tasks in ASP.NET Core.

Use Cases:

  • Email processing
  • Queue processing
  • Scheduled jobs
  • Background synchronization

Methods:

  • StartAsync()
  • StopAsync()

18. What is the difference between minimal APIs and traditional controllers?

Minimal APIs Controllers
Lightweight Structured architecture
Less boilerplate code Better for large projects
Suitable for small APIs Suitable for enterprise applications

19. How do you implement caching in .NET Core?

Types of Caching:

  • In-Memory Caching
  • Distributed Caching
  • Response Caching

In-Memory Cache Example:

    builder.Services.AddMemoryCache();
    

Redis Distributed Cache Example:

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

20. Explain how EF Core handles migrations and database seeding.

Migrations:

Migrations are used to update the database schema.

Commands:

    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

Database Seeding:

    modelBuilder.Entity<Role>().HasData(
        new Role { Id = 1, Name = "Admin" }
    );
    

21. What are gRPC services, and how do they integrate with .NET Core?

gRPC is a high-performance remote procedure call framework.

Advantages:

  • Fast communication
  • Uses Protocol Buffers
  • Strongly typed contracts
  • Efficient for microservices

Use Cases:

  • Microservices communication
  • Internal APIs
  • High-performance systems

22. How do you containerize a .NET Core API with Docker?

Dockerfile Example:

    FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
    WORKDIR /app

    FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
    WORKDIR /src

    COPY . .
    RUN dotnet publish -c Release -o /app/publish

    FROM base AS final
    WORKDIR /app
    COPY --from=build /app/publish .

    ENTRYPOINT ["dotnet", "MyApi.dll"]
    

Docker Commands:

    docker build -t myapi .
    docker run -p 8080:80 myapi
    

23. How do you secure .NET Core APIs using JWT and IdentityServer?

JWT Security:

  • Stateless authentication
  • Token-based security
  • Used in APIs and microservices

IdentityServer:

IdentityServer is an OpenID Connect and OAuth 2.0 framework for centralized authentication.

Benefits:

  • Single Sign-On
  • Centralized authentication
  • Secure API access

24. Explain the concept of background services using BackgroundService in .NET Core.

BackgroundService is a base class used to create long-running background tasks.

Example:

    public class WorkerService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1000);
            }
        }
    }
    

Use Cases:

  • Email sending
  • Queue processing
  • Log processing
  • Notification services

Additional Important .NET Interview Topics

Entity Framework Core

  • DbContext
  • DbSet
  • LINQ Queries
  • Migrations
  • Repository Pattern
  • Unit of Work

Microservices Concepts

  • API Gateway
  • Service Discovery
  • Circuit Breaker
  • Distributed Logging
  • Message Queue

Cloud and DevOps

  • Azure App Service
  • Azure Functions
  • Docker
  • Kubernetes
  • CI/CD Pipelines

Important SQL Topics

  • Stored Procedures
  • Joins
  • Indexes
  • Transactions
  • Normalization
  • Optimization

Common HR Questions

  • Tell me about yourself
  • Explain your current project
  • What challenges did you face?
  • Why should we hire you?
  • Why do you want to switch?

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.