Advanced .NET Core Web API Interview Questions

.NET Core Web API Interview Questions

General Questions

1.     What is .NET Core and how does it differ from .NET Framework?
Answer: .NET Core is a cross-platform, open-source framework for building modern applications, while .NET Framework is Windows-only and has been around longer. .NET Core is more modular and can run on Windows, Linux, and macOS.
Use Case: Choose .NET Core when you need to build cross-platform applications or microservices that can run on various operating systems.

2.     Explain the middleware pipeline in http://ASP.NET Core.
Answer: Middleware in http://ASP.NET Core is software that's assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request to the next component or handle it directly.
Example:

app.Use(async (context, next) =>

{

    // Perform some action before the next middleware

    await next.Invoke();

    // Perform some action after the next middleware

});

3.     What is Dependency Injection and how is it implemented in .NET Core?
Answer: Dependency Injection (DI) is a design pattern used to implement IoC, allowing the creation of dependent objects outside of a class and providing those objects to a class through various ways. In .NET Core, it is built-in and configured in the Startup.cs file using services like AddSingleton, AddScoped, and AddTransient.
Example:

services.AddSingleton<IMyService, MyService>();

services.AddScoped<IMyRepository, MyRepository>();

services.AddTransient<IEmailSender, EmailSender>();

4.     What are the differences between AddSingleton, AddScoped, and AddTransient?
Answer:

·       AddSingleton: Creates a single instance for the entire application lifetime.

·       AddScoped: Creates an instance per HTTP request.

·       AddTransient: Creates a new instance every time it is requested.
Use Case:

·       Use AddSingleton for services that should have a single instance, such as a configuration service.

·       Use AddScoped for services that should have a new instance per HTTP request, such as a repository.

·       Use AddTransient for lightweight, stateless services.

5.     What is Entity Framework Core and how does it differ from Entity Framework?
Answer: EF Core is a lightweight, extensible, and cross-platform version of the Entity Framework. EF Core is designed for .NET Core applications, whereas Entity Framework is for .NET Framework applications.
Use Case: Use EF Core when building .NET Core applications that require object-relational mapping (ORM) and database access.

Advanced .NET Core Questions

6.     How would you handle configuration in a .NET Core application?
Answer: Configuration in .NET Core is handled using the Configuration object, which can read settings from various sources like JSON files, environment variables, and command-line arguments.
Example:

var configuration = new ConfigurationBuilder()

    .SetBasePath(Directory.GetCurrentDirectory())

    .AddJsonFile("appsettings.json")

    .AddEnvironmentVariables()

    .Build();

7.     What is the purpose of the Program.cs file in a .NET Core project?
Answer: The Program.cs file is the entry point of a .NET Core application. It configures and runs the web host which will listen for HTTP requests.
Example:

public static void Main(string[] args)

{

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

}

 

public static IHostBuilder CreateHostBuilder(string[] args) =>

    Host.CreateDefaultBuilder(args)

        .ConfigureWebHostDefaults(webBuilder =>

        {

            webBuilder.UseStartup<Startup>();

        });

8.     How do you implement logging in .NET Core?
Answer: Logging in .NET Core can be implemented using the built-in logging framework which supports various providers like Console, Debug, EventSource, and more. Logging is configured in the Program.cs and Startup.cs files.
Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddLogging(builder =>

    {

        builder.AddConsole();

        builder.AddDebug();

    });

}

9.     What is the purpose of the IConfiguration interface in .NET Core?
Answer: IConfiguration is used to represent a set of key/value application configuration properties. It helps to access settings from appsettings.json, environment variables, etc.
Use Case: Use IConfiguration to retrieve configuration values in your application, such as database connection strings or API keys.

10.  Explain the difference between IApplicationBuilder and IWebHostBuilder.
Answer: IApplicationBuilder is used to configure the HTTP request pipeline, whereas IWebHostBuilder is used to configure the server and set up the host for the application.
Use Case:

·       Use IApplicationBuilder to configure middleware in the request pipeline.

·       Use IWebHostBuilder to configure the web host, such as specifying the content root or enabling IIS integration.

Security and Authentication

11.  How do you implement JWT authentication in .NET Core?
Answer: JWT authentication is implemented by configuring the authentication middleware to validate tokens and use JwtBearer scheme. Configure it in the Startup.cs file by adding the required services and middleware.
Example:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

    .AddJwtBearer(options =>

    {

        options.TokenValidationParameters = new TokenValidationParameters

        {

            ValidateIssuer = true,

            ValidateAudience = true,

            ValidateLifetime = true,

            ValidIssuer = Configuration["Jwt:Issuer"],

            ValidAudience = Configuration["Jwt:Audience"],

            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))

        };

    });

12.  What are the key components of JWT?
Answer: The key components of JWT are Header, Payload, and Signature. The header typically consists of the type of token and the hashing algorithm used. The payload contains the claims. The signature is used to verify the token's integrity.
Use Case: JWT is commonly used for stateless authentication in web applications, where the client includes the token in the request headers to authenticate with the server.

13.  How would you handle CORS in .NET Core?
Answer: CORS can be handled by adding the CORS middleware in the Startup.cs file and configuring it with the allowed origins, methods, and headers.
Example:

services.AddCors(options =>

{

    options.AddPolicy("AllowSpecificOrigin",

        builder => builder.WithOrigins("<http://example.com>")

                          .AllowAnyMethod()

                          .AllowAnyHeader());

});

app.UseCors("AllowSpecificOrigin");

14.  What is CSRF and how can you prevent it in .NET Core?
Answer: CSRF (Cross-Site Request Forgery) is an attack that forces a user to execute unwanted actions on a web application. It can be prevented by using anti-forgery tokens in http://ASP.NET Core.
Example:

services.AddControllersWithViews(options =>

{

    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

});

// In Razor views:

<form method="post">

    @Html.AntiForgeryToken()

    <!-- Form fields -->

</form>

15.  How do you implement role-based authorization in .NET Core?
Answer: Role-based authorization is implemented by decorating controllers or actions with the [Authorize(Roles = "RoleName")] attribute and configuring roles in the identity setup.
Example:

[Authorize(Roles = "Admin")]

public class AdminController : Controller

{

    // Controller actions accessible only to users with "Admin" role

}

Entity Framework Core Questions

16.  How do you configure a DbContext in EF Core?
Answer: DbContext is configured in the Startup.cs file using the AddDbContext method where the connection string and provider (e.g., SQL Server) are specified.
Example:

services.AddDbContext<MyDbContext>(options =>

    options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));

17.  What are migrations in EF Core and how do you use them?
Answer: Migrations in EF Core are a way to incrementally apply schema changes to the database. They are created using the Add-Migration command and applied using the Update-Database command.
Example:

dotnet ef migrations add InitialCreate

dotnet ef database update

18.  How do you implement lazy loading in EF Core?
Answer: Lazy loading in EF Core can be enabled by installing the Microsoft.EntityFrameworkCore.Proxies package and using the UseLazyLoadingProxies method when configuring the DbContext.
Example:

services.AddDbContext<MyDbContext>(options =>

    options.UseSqlServer(Configuration.GetConnectionString("MyConnection"))

           .UseLazyLoadingProxies());

19.  What is the purpose of the OnModelCreating method in EF Core?
Answer: The OnModelCreating method is used to configure the model and relationships between entities using the Fluent API.
Example:

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

    modelBuilder.Entity<Student>()

        .HasMany(s => s.Courses)

        .WithMany(c => c.Students)

        .UsingEntity(j => j.ToTable("StudentCourse"));

}

20.  How do you handle concurrency in EF Core?
Answer: Concurrency in EF Core can be handled by using a concurrency token, such as a timestamp column, and configuring the entity to use it for concurrency checks.
Example:

public class Student

{

    public int Id { get; set; }

    public string Name { get; set; }

    [Timestamp]

    public byte[] RowVersion { get; set;

 

 }

}

API Questions

21.  What is REST and how does it differ from SOAP?
Answer: REST (Representational State Transfer) is an architectural style that uses HTTP for communication and is stateless. SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information and is more complex and rigid.
Use Case: REST is commonly used for building web APIs due to its simplicity and scalability, while SOAP is used in enterprise environments with strict contracts and security requirements.

22.  How do you create a RESTful API in .NET Core?
Answer: A RESTful API in .NET Core is created by defining controllers that inherit from ControllerBase and defining endpoints using attributes like [HttpGet], [HttpPost], etc.
Example:

[ApiController]

[Route("api/[controller]")]

public class StudentsController : ControllerBase

{

    [HttpGet]

    public IEnumerable<Student> Get()

    {

        // Retrieve and return students

    }

    [HttpPost]

    public IActionResult Post(Student student)

    {

        // Create a new student

    }

}

23.  How do you implement versioning in .NET Core Web API?
Answer: Versioning in .NET Core Web API can be implemented using route-based versioning, query string-based versioning, header-based versioning, or using a custom solution.
Example (Route-based versioning):

[ApiVersion("1.0")]

[Route("api/v{version:apiVersion}/[controller]")]

public class StudentsController : ControllerBase

{

    // Controller actions for version 1.0

}

[ApiVersion("2.0")]

[Route("api/v{version:apiVersion}/[controller]")]

public class StudentsV2Controller : ControllerBase

{

    // Controller actions for version 2.0

}

24.  How do you handle exceptions in .NET Core Web API?
Answer: Exceptions in .NET Core Web API can be handled using middleware, such as a global exception handler, to catch and log exceptions and return appropriate responses.
Example:

app.UseExceptionHandler(errorApp =>

{

    errorApp.Run(async context =>

    {

        context.Response.StatusCode = 500;

        context.Response.ContentType = "application/json";

        var error = context.Features.Get<IExceptionHandlerFeature>();

        if (error != null)

        {

            var ex = error.Error;

            await context.Response.WriteAsync(JsonConvert.SerializeObject(new

            {

                message = ex.Message

            }));

        }

    });

});

25.  What are filters in http://ASP.NET Core and how do you use them?
Answer: Filters in http://ASP.NET Core are used to run code before or after certain stages in the request processing pipeline. They can be used for authorization, error handling, caching, etc.
Example (Action Filter):

public class CustomActionFilter : IActionFilter

{

    public void OnActionExecuting(ActionExecutingContext context)

    {

        // Perform some action before the action executes

    }

    public void OnActionExecuted(ActionExecutedContext context)

    {

        // Perform some action after the action executes

    }

}

// Apply the filter to a controller or action:

[ServiceFilter(typeof(CustomActionFilter))]

public IActionResult Index()

{

    // Action logic

}

26.  How do you handle pagination in a .NET Core Web API?
Answer: Pagination is the process of dividing a large set of data into smaller, more manageable chunks or pages. In a .NET Core Web API, pagination can be handled by accepting query parameters for page size and page number, and modifying the database query to return only the requested subset of data.
Use Case: Pagination is useful when dealing with large datasets that cannot be efficiently returned in a single response. It allows clients to retrieve data in smaller chunks, improving performance and reducing the amount of data transferred over the network.
Example:

[HttpGet]

public IActionResult GetProducts(int pageNumber = 1, int pageSize = 10)

{

    var products = _context.Products

        .Skip((pageNumber - 1) * pageSize)

        .Take(pageSize)

        .ToList();

    return Ok(products);

}

27.  What is the significance of IServiceCollection and IServiceProvider in .NET Core?
Answer: In .NET Core, IServiceCollection and IServiceProvider are key interfaces used for dependency injection and service resolution.

·       IServiceCollection represents a collection of service descriptors. It is used to register services with their corresponding implementations or instances. Services can be registered as singletons, scoped, or transient.

·       IServiceProvider represents a container that provides access to the registered services. It is responsible for resolving and creating instances of the services when they are requested.
Use Case: IServiceCollection and IServiceProvider are used extensively in .NET Core for managing dependencies and promoting loose coupling between components. By registering services in the IServiceCollection and resolving them through the IServiceProvider, you can easily swap implementations, mock dependencies for testing, and manage the lifetime of service instances.
Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddSingleton<IMyService, MyService>();

    services.AddScoped<IMyRepository, MyRepository>();

    services.AddTransient<IEmailSender, EmailSender>();

}

 

public class MyController : ControllerBase

{

    private readonly IMyService _myService;

    public MyController(IMyService myService)

    {

        _myService = myService;

    }

    // Action methods can use the injected service

}

Additional Important Questions for .NET Core 8 and C#

28.  What is .NET Core 8 and what are its new features?
Answer: .NET Core 8 is the latest version of the .NET Core framework. New features include performance improvements, new APIs, enhanced support for cloud-native applications, and improved developer productivity tools.
Use Case: Use .NET Core 8 for building modern, high-performance, and scalable applications with the latest enhancements and features.

29.  How do you use nullable reference types in C#?
Answer: Nullable reference types in C# allow you to explicitly specify whether a reference type can be null. This helps to avoid null reference exceptions by providing compile-time warnings.
Example:

public class Person

{

    public string? FirstName { get; set; } // Nullable

    public string LastName { get; set; } // Non-nullable

}

30.  What are records in C# and how do they differ from classes?
Answer: Records in C# are a new reference type that provides built-in functionality for value equality, immutability, and with-expressions. They are designed to be used for data-centric applications.
Example:

public record Person(string FirstName, string LastName);

31.  How do you implement global exception handling in .NET Core 8?
Answer: Global exception handling can be implemented using middleware to catch and log exceptions globally.
Example:

app.UseExceptionHandler(errorApp =>

{

    errorApp.Run(async context =>

    {

        context.Response.StatusCode = 500;

        context.Response.ContentType = "application/json";

        var error = context.Features.Get<IExceptionHandlerFeature>();

        if (error != null)

        {

            var ex = error.Error;

            await context.Response.WriteAsync(JsonConvert.SerializeObject(new

            {

                message = ex.Message

            }));

        }

    });

});

32.  How do you use pattern matching enhancements in C# 8?
Answer: C# 8 introduces enhanced pattern matching capabilities, such as switch expressions, property patterns, and positional patterns.
Example:

public string GetDescription(object obj) => obj switch

{

    Person p => $"Person: {p.FirstName} {p.LastName}",

    _ => "Unknown"

};

33.  What is Blazor and how can you use it with .NET Core 8?
Answer: Blazor is a framework for building interactive web UIs using C# and .NET. Blazor WebAssembly allows running .NET code directly in the browser.
Use Case: Use Blazor to build client-side web applications with C# instead of JavaScript.
Example:

@page "/counter"

<h1>Counter</h1>

 

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

 

@code {

    private int currentCount = 0;

    private void IncrementCount()

    {

        currentCount++;

    }

}

34.  What is the difference between IEnumerable and IQueryable in .NET Core?
Answer: IEnumerable and IQueryable are both interfaces used for querying data in .NET Core, but they have different behaviors.

·       IEnumerable is used for in-memory querying and executes the query immediately, returning the result as a collection of objects.

·       IQueryable is used for deferred execution and builds an expression tree that can be translated into a query language (e.g., SQL) for execution against a data source.
Use Case: Use IEnumerable when working with in-memory collections or when you need immediate execution. Use IQueryable when querying data from a database or other external data source, as it allows for deferred execution and query optimization.
Example:

// IEnumerable example

var numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = numbers.Where(x => x % 2 == 0);

 

// IQueryable example

var context = new MyDbContext();

var students = context.Students.Where(s =>

 

 s.Age > 20);

35.  How do you implement caching in a .NET Core Web API?
Answer: Caching in a .NET Core Web API can be implemented using the IMemoryCache interface or distributed caching options like Redis.
Use Case: Caching is used to improve performance by storing frequently accessed data in memory, reducing the need to retrieve data from the database or external services on each request.
Example:

public class MyController : ControllerBase

{

    private readonly IMemoryCache _cache;

    public MyController(IMemoryCache cache)

    {

        _cache = cache;

    }

    [HttpGet]

    public IActionResult GetData()

    {

        if (!_cache.TryGetValue("myKey", out string cachedData))

        {

            // Data not found in cache, retrieve from database or external service

            string data = GetDataFromDatabase();

            // Store data in cache

            _cache.Set("myKey", data, new MemoryCacheEntryOptions

            {

                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)

            });

            cachedData = data;

        }

        return Ok(cachedData);

    }

}

36.  What are the different options for database providers in Entity Framework Core?
Answer: Entity Framework Core supports various database providers, including:

·       Microsoft.EntityFrameworkCore.SqlServer: SQL Server database provider

·       Microsoft.EntityFrameworkCore.SQLite: SQLite database provider

·       Microsoft.EntityFrameworkCore.InMemory: In-memory database provider for testing

·       Microsoft.EntityFrameworkCore.Cosmos: Azure Cosmos DB provider

·       Microsoft.EntityFrameworkCore.PostgreSQL: PostgreSQL database provider

·       Microsoft.EntityFrameworkCore.MySql: MySQL database provider
Use Case: Choose the appropriate database provider based on your project's requirements and the database system you are using.

37.  How do you implement health checks in a .NET Core Web API?
Answer: Health checks in a .NET Core Web API can be implemented using the Microsoft.Extensions.Diagnostics.HealthChecks package. Health checks allow monitoring the health and availability of the API and its dependencies.
Use Case: Health checks are useful for monitoring the status of the API and its dependencies, such as databases, external services, or file systems. They help in identifying and troubleshooting issues.
Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddHealthChecks()

        .AddSqlServer(Configuration["ConnectionStrings:DefaultConnection"])

        .AddUrlGroup(new Uri("<https://example.com/api/status>"));

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseEndpoints(endpoints =>

    {

        endpoints.MapHealthChecks("/health");

    });

}

38.  What is the purpose of the IOptions interface in .NET Core?
Answer: The IOptions interface in .NET Core is used for accessing configuration settings in a strongly-typed manner. It allows you to bind configuration values to a class and inject them into your services.
Use Case: Use IOptions when you have configuration settings that need to be accessed in a strongly-typed way across your application.
Example:

public class MySettings

{

    public string ApiKey { get; set; }

    public int MaxRetries { get; set; }

}

 

public void ConfigureServices(IServiceCollection services)

{

    services.Configure<MySettings>(Configuration.GetSection("MySettings"));

}

 

public class MyService

{

    private readonly MySettings _settings;

    public MyService(IOptions<MySettings> options)

    {

        _settings = options.Value;

    }

}

39.  What is the difference between async and await keywords in C#?
Answer: The async keyword is used to define an asynchronous method, while the await keyword is used to pause the execution of an asynchronous method until a task completes.
Use Case: Asynchronous programming is used to improve the responsiveness and performance of applications by allowing long-running operations to be executed without blocking the main thread.
Example:

public async Task<IActionResult> GetDataAsync()

{

    var data = await _repository.GetDataAsync();

    return Ok(data);

}

40.  What are the benefits of using the IHttpClientFactory in .NET Core?
Answer: The IHttpClientFactory is a service that manages the lifetime of HttpClient instances in .NET Core. It provides benefits such as:

·       Centralized configuration and management of HttpClient instances.

·       Automatic handling of DNS changes and endpoint binding.

·       Improved performance by reusing HttpClient instances.
Use Case: Use IHttpClientFactory when making HTTP requests from your .NET Core application to external services or APIs.
Example:

public class MyService

{

    private readonly HttpClient _httpClient;

    public MyService(IHttpClientFactory httpClientFactory)

    {

        _httpClient = httpClientFactory.CreateClient("MyNamedClient");

    }

    public async Task<string> GetDataAsync()

    {

        var response = await _httpClient.GetAsync("<https://api.example.com/data>");

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();

    }

}

41.  How do you handle model validation in .NET Core Web API?
Answer: Model validation in .NET Core Web API can be handled using data annotations and the ModelState property in controllers. Data annotations are used to specify validation rules for model properties, while ModelState represents the state of the model during the validation process.
Use Case: Model validation is important to ensure that the data received from the client meets the expected format and constraints before processing it further.
Example:

public class User

{

    [Required]

    public string Name { get; set; }

    [EmailAddress]

    public string Email { get; set; }

}

 

[HttpPost]

public IActionResult CreateUser(User user)

{

    if (!ModelState.IsValid)

    {

        return BadRequest(ModelState);

    }

    // Process the valid user object

    // ...

    return Ok();

}

42.  What are the different ways to handle cross-origin resource sharing (CORS) in .NET Core?
Answer: CORS in .NET Core can be handled using the built-in CORS middleware or by using the [EnableCors] attribute on controllers or actions. The CORS middleware allows you to define global CORS policies, while the attribute allows you to specify CORS policies at a more granular level.
Use Case: CORS is used to control access to resources (APIs) from different origins (domains) in web applications.
Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddCors(options =>

    {

        options.AddPolicy("AllowSpecificOrigin",

            builder => builder.WithOrigins("<http://example.com>")

                              .AllowAnyMethod()

                              .AllowAnyHeader());

    });

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseCors("AllowSpecificOrigin");

    // ...

}

43.  How do you implement rate limiting in .NET Core Web API?
Answer: Rate limiting in .NET Core Web API can be implemented using middleware or libraries like AspNetCoreRateLimit. Rate limiting helps to control the number of requests a client can make to an API within a specified time window.
Use Case: Rate limiting is used to prevent abuse, protect against denial-of-service attacks, and ensure fair usage of API resources.
Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddOptions();

    services.AddMemoryCache();

    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseIpRateLimiting();

    // ...

}

44.  What are the different ways to handle authentication and authorization in .NET Core Web API?
Answer: Authentication and authorization in .NET Core Web API can be handled using various approaches, such as:

·       JWT (JSON Web Tokens) authentication

·       Cookie-based authentication

·       Identity Server (OAuth 2.0 and OpenID Connect)

·       Custom authentication middleware
Use Case: Authentication and authorization are used to secure the API endpoints and ensure that only authenticated and authorized users can access the protected resources.
Example (JWT Authentication):

public void ConfigureServices(IServiceCollection services)

{

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

        .AddJwtBearer(options =>

        {

            options.TokenValidationParameters = new TokenValidationParameters

            {

                ValidateIssuer = true,

                ValidateAudience = true,

                ValidateLifetime = true,

                ValidIssuer = Configuration["Jwt:Issuer"],

                ValidAudience = Configuration["Jwt:Audience"],

                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))

            };

        });

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseAuthentication();

    app.UseAuthorization();

    // ...

}

 

[Authorize]

[HttpGet]

public IActionResult GetData()

{

    // Access protected resource

    // ...

}

Additional Questions

45.  What is the purpose of the IHostedService interface in .NET Core?
Answer: The IHostedService interface in .NET Core is used to implement background tasks or hosted services that run in the background independently of the HTTP request pipeline. It allows you to execute long-running tasks, scheduled jobs, or continuous processing within the application's lifetime.
Use Case: Hosted services are useful when you need

to perform background operations, such as data synchronization, queue processing, or periodic tasks, without impacting the responsiveness of the API.
Example:

public class MyHostedService : IHostedService

{

    private readonly ILogger<MyHostedService> _logger;

    public MyHostedService(ILogger<MyHostedService> logger)

    {

        _logger = logger;

    }

    public Task StartAsync(CancellationToken cancellationToken)

    {

        _logger.LogInformation("Hosted service started.");

        // Perform startup tasks or initialize resources

        return Task.CompletedTask;

    }

    public Task StopAsync(CancellationToken cancellationToken)

    {

        _logger.LogInformation("Hosted service stopped.");

        // Perform cleanup tasks or release resources

        return Task.CompletedTask;

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddHostedService<MyHostedService>();

    // ...

}

46.  How do you handle API versioning using the Microsoft.AspNetCore.Mvc.Versioning package?
Answer: The Microsoft.AspNetCore.Mvc.Versioning package provides a way to implement API versioning in .NET Core Web API. It supports various versioning schemes such as URL versioning, header versioning, and media type versioning. You can configure versioning options and apply version-specific attributes to controllers and actions.
Use Case: API versioning is important when evolving APIs over time to introduce new features, change existing functionality, or deprecate old endpoints while maintaining backward compatibility.
Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddApiVersioning(options =>

    {

        options.DefaultApiVersion = new ApiVersion(1, 0);

        options.AssumeDefaultVersionWhenUnspecified = true;

        options.ReportApiVersions = true;

    });

    // ...

}

 

// In controllers

[ApiVersion("1.0")]

[Route("api/v{version:apiVersion}/[controller]")]

public class UsersController : ControllerBase

{

    // ...

}

 

[ApiVersion("2.0")]

[Route("api/v{version:apiVersion}/[controller]")]

public class UsersV2Controller : ControllerBase

{

    // ...

}

47.  What are some strategies for implementing API caching using response caching in .NET Core?
Answer: Response caching in .NET Core allows you to cache the entire response of an API endpoint. You can use the [ResponseCache] attribute on controllers or actions to specify caching options such as duration, location, and vary-by headers. The cached responses can be stored in memory or distributed caches like Redis.
Use Case: Response caching is useful when you have API endpoints that return data that doesn't change frequently and can be served from the cache. It helps reduce the load on the server, improve response times, and minimize the overhead of generating the same response multiple times.
Example:

[HttpGet]

[ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new[] { "id" })]

public IActionResult GetProduct(int id)

{

    var product = _repository.GetProductById(id);

    if (product == null)

    {

        return NotFound();

    }

    return Ok(product);

}

48.  How do you handle API request logging and tracing in .NET Core using Serilog?
Answer: Serilog is a popular logging library that integrates well with .NET Core. You can use Serilog to log API requests and trace the flow of execution in your application. By configuring Serilog with various sinks (e.g., console, file, database), you can capture and store log messages for later analysis and troubleshooting.
Use Case: API request logging and tracing are essential for monitoring the usage and behavior of your API. It helps in debugging issues, identifying performance bottlenecks, and gaining insights into how your API is being consumed by clients.
Example:

// In Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>

    Host.CreateDefaultBuilder(args)

        .ConfigureWebHostDefaults(webBuilder =>

        {

            webBuilder.UseStartup<Startup>();

        })

        .UseSerilog((hostingContext, loggerConfiguration) =>

        {

            loggerConfiguration

                .ReadFrom.Configuration(hostingContext.Configuration)

                .Enrich.FromLogContext()

                .WriteTo.Console()

                .WriteTo.File("logs/api.txt", rollingInterval: RollingInterval.Day);

        });

 

// In controllers

public class ProductsController : ControllerBase

{

    private readonly ILogger<ProductsController> _logger;

    public ProductsController(ILogger<ProductsController> logger)

    {

        _logger = logger;

    }

    [HttpGet("{id}")]

    public IActionResult GetProduct(int id)

    {

        _logger.LogInformation("Getting product with ID: {ProductId}", id);

        // ...

    }

}

49.  What are some considerations for implementing API security using API keys and JWT tokens in .NET Core?
Answer: API security in .NET Core can be implemented using a combination of API keys and JWT (JSON Web Tokens) tokens. API keys can be used to authenticate clients and grant them access to the API, while JWT tokens can be used to authenticate and authorize individual requests. You can configure API key validation middleware and JWT authentication middleware in the Startup.cs file.
Use Case: Implementing API security using API keys and JWT tokens helps protect your API from unauthorized access and ensures that only authenticated and authorized clients can consume your API endpoints. API keys are often used for client-level authentication, while JWT tokens are used for user-level authentication and authorization.
Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddAuthentication(options =>

    {

        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    })

    .AddJwtBearer(options =>

    {

        options.TokenValidationParameters = new TokenValidationParameters

        {

            ValidateIssuer = true,

            ValidateAudience = true,

            ValidateLifetime = true,

            ValidIssuer = Configuration["Jwt:Issuer"],

            ValidAudience = Configuration["Jwt:Audience"],

            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))

        };

    });

    services.AddSingleton<IApiKeyValidator, ApiKeyValidator>();

    // ...

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseMiddleware<ApiKeyValidationMiddleware>();

    app.UseAuthentication();

    app.UseAuthorization();

    // ...

}

 

// API key validation middleware

public class ApiKeyValidationMiddleware

{

    private readonly RequestDelegate _next;

    private readonly IApiKeyValidator _apiKeyValidator;

    public ApiKeyValidationMiddleware(RequestDelegate next, IApiKeyValidator apiKeyValidator)

    {

        _next = next;

        _apiKeyValidator = apiKeyValidator;

    }

    public async Task InvokeAsync(HttpContext context)

    {

        if (!context.Request.Headers.TryGetValue("X-API-KEY", out var apiKey))

        {

            context.Response.StatusCode = 401;

            await context.Response.WriteAsync("API key is missing.");

            return;

        }

        if (!_apiKeyValidator.IsValid(apiKey))

        {

            context.Response.StatusCode = 401;

            await context.Response.WriteAsync("Invalid API key.");

            return;

        }

        await _next(context);

    }

}

 

// In controllers

[Authorize]

[HttpGet]

public IActionResult GetData()

{

    // Access protected resource

    // ...

}

Final Additions

50.  What is the purpose of the IWebHostEnvironment interface in .NET Core?
Answer: The IWebHostEnvironment interface provides information about the hosting environment in which the application is running. It allows you to access details such as the environment name (e.g., Development, Staging, Production), content root path, web root path, and whether the application is running in a development environment.
Use Case: The IWebHostEnvironment interface is useful when you need to adapt your application's behavior based on the hosting environment. For example, you might want to enable detailed error messages in the development environment but not in production, or load different configuration files based on the environment.
Example:

public class MyController : ControllerBase

{

    private readonly IWebHostEnvironment _env;

    public MyController(IWebHostEnvironment env)

    {

        _env = env;

    }

    [HttpGet]

    public IActionResult GetData()

    {

        if (_env.IsDevelopment())

        {

            // Enable detailed error messages in development

            var detailedErrorMessage = "Detailed error message";

            return StatusCode(500, detailedErrorMessage);

        }

        else

        {

            // Return a generic error message in production

            return StatusCode(500, "An error occurred.");

        }

    }

}

51.  How do you handle API versioning using the AcceptHeaderApiVersionReader in .NET Core?
Answer: The AcceptHeaderApiVersionReader is a version reader provided by the Microsoft.AspNetCore.Mvc.Versioning package that allows you to specify the API version using the Accept header in the request. You can configure the version reader in the Startup.cs file and define the version format and parameter name.
Use Case: Using the Accept header for API versioning is a common approach when you want to allow clients to specify the desired API version explicitly in the request headers. It provides a clean and standard way to version your API endpoints.
Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddApiVersioning(options =>

    {

        options.ApiVersionReader = new AcceptHeaderApiVersionReader("X-API-Version");

    });

    // ...

}

 

// In controllers

[ApiVersion("1.0")]

[

 

Route("api/[controller]")]

public class UsersController : ControllerBase

{

    // ...

}

 

[ApiVersion("2.0")]

[Route("api/[controller]")]

public class UsersV2Controller : ControllerBase

{

    // ...

}

52.  What are some strategies for implementing API caching using ETags in .NET Core?
Answer: ETags (Entity Tags) are a caching mechanism that allows clients to make conditional requests to the server. In .NET Core, you can use the [ResponseCache] attribute with the VaryByHeader property to generate ETags based on the response content. When a client sends a request with an If-None-Match header containing the ETag, the server can compare it with the current ETag and return a 304 Not Modified response if the content hasn't changed.
Use Case: ETags are useful for optimizing network usage and reducing the amount of data transferred between the client and the server. They allow clients to cache responses and make conditional requests to retrieve updated content only when necessary.
Example:

[HttpGet("{id}")]

[ResponseCache(Duration = 3600, VaryByHeader = "ETag")]

public IActionResult GetProduct(int id)

{

    var product = _repository.GetProductById(id);

    if (product == null)

    {

        return NotFound();

    }

    var etag = GenerateETag(product);

    HttpContext.Response.Headers.Add("ETag", etag);

    return Ok(product);

}

 

private string GenerateETag(Product product)

{

    // Generate a unique ETag based on the product data

    // Example: Use a hash of the product's properties

    var json = JsonConvert.SerializeObject(product);

    using (var sha256 = SHA256.Create())

    {

        var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(json));

        return BitConverter.ToString(hash).Replace("-", "");

    }

}

53.  How do you handle API request tracing using correlation IDs in .NET Core?
Answer: Correlation IDs are unique identifiers that are assigned to each request and propagated throughout the application to trace the flow of execution. In .NET Core, you can use middleware to generate and assign a correlation ID to each incoming request. The correlation ID can then be included in log messages, exception details, and even propagated to downstream services for end-to-end tracing.
Use Case: Correlation IDs are useful for tracing and debugging distributed systems. They allow you to correlate log messages and trace the flow of a request across multiple services or components, making it easier to identify and diagnose issues.
Example:

// Correlation ID middleware

public class CorrelationIdMiddleware

{

    private readonly RequestDelegate _next;

    private const string CorrelationIdHeaderName = "X-Correlation-ID";

    public CorrelationIdMiddleware(RequestDelegate next)

    {

        _next = next;

    }

    public async Task InvokeAsync(HttpContext context)

    {

        string correlationId = null;

        if (context.Request.Headers.TryGetValue(CorrelationIdHeaderName, out var correlationIdHeader))

        {

            correlationId = correlationIdHeader.FirstOrDefault();

        }

        else

        {

            correlationId = Guid.NewGuid().ToString();

            context.Request.Headers[CorrelationIdHeaderName] = correlationId;

        }

        context.Response.OnStarting(() =>

        {

            context.Response.Headers[CorrelationIdHeaderName] = correlationId;

            return Task.CompletedTask;

        });

        using (LogContext.PushProperty("CorrelationId", correlationId))

        {

            await _next(context);

        }

    }

}

 

// In Startup.cs

public void Configure(IApplicationBuilder app)

{

    app.UseMiddleware<CorrelationIdMiddleware>();

    // ...

}

 

// In controllers or services

public class ProductsController : ControllerBase

{

    private readonly ILogger<ProductsController> _logger;

    public ProductsController(ILogger<ProductsController> logger)

    {

        _logger = logger;

    }

    [HttpGet("{id}")]

    public IActionResult GetProduct(int id)

    {

        // Log messages with correlation ID

        _logger.LogInformation("Getting product with ID: {ProductId}", id);

        // ...

    }

}

54.  What are some considerations for implementing API rate limiting based on client IP in .NET Core?
Answer: API rate limiting based on client IP can be implemented in .NET Core using middleware or libraries like AspNetCoreRateLimit. You can configure the rate limiting rules based on the client IP address, specifying the maximum number of requests allowed within a given time window. If a client exceeds the rate limit, the API can return a 429 Too Many Requests response.
Use Case: Implementing API rate limiting based on client IP helps protect your API from abuse and ensures fair usage among clients. It allows you to control the rate at which individual clients can access your API endpoints, preventing excessive or abusive requests from a single IP address.
Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddOptions();

    services.AddMemoryCache();

    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

    services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseIpRateLimiting();

    // ...

}

 

// In appsettings.json

{

  "IpRateLimiting": {

    "EnableEndpointRateLimiting": true,

    "StackBlockedRequests": false,

    "RealIpHeader": "X-Real-IP",

    "ClientIdHeader": "X-ClientId",

    "HttpStatusCode": 429,

    "GeneralRules": [

      {

        "Endpoint": "*",

        "Period": "1m",

        "Limit": 100

      }

    ]

  },

  "IpRateLimitPolicies": {

    "IpRules": [

      {

        "Ip": "84.247.85.224",

        "Rules": [

          {

            "Endpoint": "*",

            "Period": "1m",

            "Limit": 50

          }

        ]

      }

    ]

  }

}

Sure, here are some additional interview questions to continue from the previous numbering:

55.  How do you implement unit testing in a .NET Core application?
Answer: Unit testing in a .NET Core application can be implemented using testing frameworks such as xUnit, NUnit, or MSTest. These frameworks provide the tools necessary to write and execute test cases, ensuring that individual units of code (e.g., methods or classes) function correctly.

Example (using xUnit):

public class Calculator

{

    public int Add(int a, int b) => a + b;

}

 

public class CalculatorTests

{

    private readonly Calculator _calculator;

 

    public CalculatorTests()

    {

        _calculator = new Calculator();

    }

 

    [Fact]

    public void Add_ShouldReturnCorrectSum()

    {

        int result = _calculator.Add(2, 3);

        Assert.Equal(5, result);

    }

}

56.  What is the purpose of the Dependency Injection (DI) container in .NET Core?
Answer: The DI container in .NET Core manages the creation, lifetime, and disposal of dependencies. It allows you to define the relationships between classes and their dependencies, promoting loose coupling and making it easier to manage the dependencies within an application.

Example:

public void ConfigureServices(IServiceCollection services)

{

    services.AddSingleton<IMyService, MyService>();

    services.AddScoped<IMyRepository, MyRepository>();

    services.AddTransient<IEmailSender, EmailSender>();

}

57.  What are some common strategies for optimizing the performance of a .NET Core application?
Answer: Common strategies for optimizing the performance of a .NET Core application include:

·       Caching: Implementing caching to store frequently accessed data.

·       Asynchronous Programming: Using async/await to improve the responsiveness of the application.

·       Database Optimization: Using efficient queries, indexes, and stored procedures.

·       Load Balancing: Distributing incoming requests across multiple servers.

·       Minimizing Network Latency: Reducing the number of network calls and optimizing data transfer.

58.  How do you handle file uploads in a .NET Core Web API?
Answer: File uploads in a .NET Core Web API can be handled using the
IFormFile interface. The uploaded files can be accessed through the HttpContext.Request.Form.Files collection and then processed or saved as needed.

Example:

[HttpPost("upload")]

public async Task<IActionResult> UploadFile(IFormFile file)

{

    if (file == null || file.Length == 0)

    {

        return BadRequest("No file uploaded.");

    }

 

    var path = Path.Combine(Directory.GetCurrentDirectory(), "uploads", file.FileName);

 

    using (var stream = new FileStream(path, FileMode.Create))

    {

        await file.CopyToAsync(stream);

    }

 

    return Ok(new { file.FileName });

}

59.  What is the purpose of the IApplicationLifetime interface in .NET Core?
Answer: The
IApplicationLifetime interface in .NET Core is used to manage the application's lifetime events. It provides events that you can hook into to run code during application startup, shutdown, and when the application is about to stop.

Example:

public class Startup

{

    public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicationLifetime)

    {

        applicationLifetime.ApplicationStarted.Register(OnApplicationStarted);

        applicationLifetime.ApplicationStopping.Register(OnApplicationStopping);

        applicationLifetime.ApplicationStopped.Register(OnApplicationStopped);

    }

 

    private void OnApplicationStarted() => Console.WriteLine("Application started.");

    private void OnApplicationStopping() => Console.WriteLine("Application stopping.");

    private void OnApplicationStopped() => Console.WriteLine("Application stopped.");

}

60.  How do you handle internationalization (i18n) and localization (l10n) in a .NET Core application?
Answer: Internationalization (i18n) and localization (l10n) in a .NET Core application can be handled using resource files and the built-in localization services. You can create resource files for different languages and use the
IStringLocalizer or IViewLocalizer to access localized strings in controllers and views.

Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddMvc().AddViewLocalization();

}

 

// In a controller

public class HomeController : Controller

{

    private readonly IStringLocalizer<HomeController> _localizer;

 

    public HomeController(IStringLocalizer<HomeController> localizer)

    {

        _localizer = localizer;

    }

 

    public IActionResult Index()

    {

        ViewData["Message"] = _localizer["WelcomeMessage"];

        return View();

    }

}

61.  What is the Mediator pattern and how is it implemented in .NET Core?
Answer: The Mediator pattern is a behavioral design pattern that promotes loose coupling by keeping objects from referring to each other explicitly. Instead, they communicate via a mediator object. In .NET Core, this pattern can be implemented using the MediatR library.

Example:

// Install-Package MediatR.Extensions.Microsoft.DependencyInjection

public class Ping : IRequest<string> {}

 

public class PingHandler : IRequestHandler<Ping, string>

{

    public Task<string> Handle(Ping request, CancellationToken cancellationToken)

    {

        return Task.FromResult("Pong");

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddMediatR(typeof(Startup));

}

 

// In a controller

public class HomeController : Controller

{

    private readonly IMediator _mediator;

 

    public HomeController(IMediator mediator)

    {

        _mediator = mediator;

    }

 

    public async Task<IActionResult> Index()

    {

        var result = await _mediator.Send(new Ping());

        return Ok(result);

    }

}

62.  What is CQRS and how is it beneficial in application development?
Answer: CQRS (Command Query Responsibility Segregation) is a pattern that separates read and write operations into different models. This can lead to better scalability and performance, as the read and write operations can be optimized independently.

Use Case: CQRS is beneficial in scenarios where read and write operations have different requirements in terms of performance, scalability, and complexity.

63.  How do you implement CQRS in .NET Core?
Answer: CQRS can be implemented in .NET Core by separating command and query handlers, often using the MediatR library.

Example:

// Command

public class CreateUserCommand : IRequest

{

    public string Name { get; set; }

}

 

// Command Handler

public class CreateUserHandler : IRequestHandler<CreateUserCommand>

{

    private readonly IUserRepository _repository;

 

    public CreateUserHandler(IUserRepository repository)

    {

        _repository = repository;

    }

 

    public async Task<Unit> Handle(CreateUserCommand request, CancellationToken cancellationToken)

    {

        var user = new User { Name = request.Name };

        await _repository.AddUserAsync(user);

        return Unit.Value;

    }

}

 

// Query

public class GetUserQuery : IRequest<User>

{

    public int UserId { get; set; }

}

 

// Query Handler

public class GetUserHandler : IRequestHandler<GetUserQuery, User>

{

    private readonly IUserRepository _repository;

 

    public GetUserHandler(IUserRepository repository)

    {

        _repository = repository;

    }

 

    public async Task<User> Handle(GetUserQuery request, CancellationToken cancellationToken)

    {

        return await _repository.GetUserByIdAsync(request.UserId);

    }

}

64.  What is the Repository pattern and why is it used?
Answer: The Repository pattern is a design pattern that provides an abstraction layer over data access logic. It helps to decouple the business logic from the data access layer, making the code more maintainable and testable.

Example:

public interface IUserRepository

{

    Task<User> GetUserByIdAsync(int id);

    Task AddUserAsync(User user);

}

 

public class UserRepository : IUserRepository

{

    private readonly MyDbContext _context;

 

    public UserRepository(MyDbContext context)

    {

        _context = context;

    }

 

    public async Task<User> GetUserByIdAsync(int id)

    {

        return await _context.Users.FindAsync(id);

    }

 

    public async Task AddUserAsync(User user)

    {

        _context.Users.Add(user);

        await _context.SaveChangesAsync();

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddScoped<IUserRepository, UserRepository>();

}

65.  How do you implement validation in .NET Core using FluentValidation?
Answer: FluentValidation is a popular library for validation in .NET Core. It provides a fluent API for building validation rules for your models.

Example:

// Install-Package FluentValidation.AspNetCore

public class User

{

    public string Name { get; set; }

    public string Email { get; set; }

}

 

public class UserValidator : AbstractValidator<User>

{

    public UserValidator()

    {

        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");

        RuleFor(x => x.Email).EmailAddress().WithMessage("Invalid email format.");

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddControllers()

            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserValidator>());

}

66.  What is the difference between synchronous and asynchronous programming in .NET Core?
Answer: Synchronous programming executes tasks sequentially, blocking the current thread until the task completes. Asynchronous programming allows tasks to run concurrently, improving responsiveness and scalability by freeing up the current thread to handle other tasks while waiting for I/O operations or long-running tasks to complete.

Use Case: Use asynchronous programming to improve the performance and responsiveness of applications that involve I/O-bound operations or long-running tasks.

67.  How do you handle background tasks in .NET Core using IHostedService?
Answer: IHostedService is used to run background tasks in .NET Core. You can create a class that implements the IHostedService interface and register it in the service collection.

Example:

public class BackgroundTaskService : IHostedService, IDisposable

{

    private Timer _timer;

 

    public Task StartAsync(CancellationToken cancellationToken)

    {

        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));

        return Task.CompletedTask;

    }

 

    private void DoWork(object state)

    {

        // Perform background work

    }

 

    public Task StopAsync(CancellationToken cancellationToken)

    {

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;

    }

 

    public void Dispose()

    {

        _timer?.Dispose();

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddHostedService<BackgroundTaskService>();

}

68.  What is the role of AutoMapper in .NET Core?
Answer: AutoMapper is a library that helps map objects from one type to another. It is commonly used to map data transfer objects (DTOs) to domain models or view models, reducing the need for manual mapping code.

Example:

// Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

public class UserProfile : Profile

{

    public UserProfile()

    {

        CreateMap<User, UserDto>();

        CreateMap<UserDto, User>();

    }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddAutoMapper(typeof(Startup));

}

 

// In a controller

public class UserController : ControllerBase

{

    private readonly IMapper _mapper;

 

    public UserController(IMapper mapper)

    {

        _mapper = mapper;

    }

 

    public IActionResult GetUser(int id)

    {

        var user = _repository.GetUserById(id);

        var userDto = _mapper.Map<UserDto>(user);

        return Ok(userDto);

    }

}

69.  How do you handle logging in .NET Core using Serilog?
Answer: Serilog is a popular logging library for .NET Core. It provides powerful and flexible logging capabilities, including structured logging.

Example:

// Install-Package Serilog.AspNetCore

public static IHostBuilder CreateHostBuilder(string[] args) =>

    Host.CreateDefaultBuilder(args)

        .UseSerilog((context, configuration) => 

            configuration.ReadFrom.Configuration(context.Configuration));

 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();

    }

    else

    {

        app.UseExceptionHandler("/Home/Error");

        app.UseHsts();

    }

 

    app.UseSerilogRequestLogging();

}

70.  How do you manage application settings in a .NET Core application?
Answer: Application settings in .NET Core are typically managed using configuration files like
appsettings.json. The configuration system is flexible and supports various sources, including environment variables and command-line arguments.

Example:

public class MySettings

{

    public string Setting1 { get; set; }

    public int Setting2 { get; set; }

}

 

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.Configure<MySettings>(Configuration.GetSection("MySettings"));

}

 

// Usage in a controller or service

public class MyService

{

    private readonly MySettings _settings;

 

    public MyService(IOptions<MySettings> options)

    {

        _settings = options.Value;

    }

}

71.  What are the key differences between http://ASP.NET Core and http://ASP.NET MVC?
Answer: http://ASP.NET Core is a cross-platform, high-performance framework for building modern applications, while http://ASP.NET MVC is a part of the older .NET Framework and is Windows-only. http://ASP.NET Core is more modular and includes features like built-in dependency injection, lightweight middleware, and improved performance.

Use Case: Use http://ASP.NET Core for new projects to take advantage of its cross-platform capabilities, improved performance, and modern architecture.

72.  How do you secure an http://ASP.NET Core application using Identity?
Answer: http://ASP.NET Core Identity is a membership system that provides login functionality. It can be configured

to use a database to store user information and integrates with authentication and authorization.

Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddDbContext<ApplicationDbContext>(options =>

        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

 

    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)

        .AddEntityFrameworkStores<ApplicationDbContext>();

 

    services.AddControllersWithViews();

}

 

// In a controller

public class AccountController : Controller

{

    private readonly UserManager<IdentityUser> _userManager;

    private readonly SignInManager<IdentityUser> _signInManager;

 

    public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)

    {

        _userManager = userManager;

        _signInManager = signInManager;

    }

 

    [HttpPost]

    public async Task<IActionResult> Login(LoginViewModel model)

    {

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

        if (result.Succeeded)

        {

            return RedirectToAction("Index", "Home");

        }

        return View(model);

    }

}

73.  What is the purpose of http://ASP.NET Core's Razor Pages?
Answer: Razor Pages is a simplified programming model for building web UI in http://ASP.NET Core. It is designed to make it easier to build web pages without the complexity of controllers and views found in MVC.

Example:

// In Startup.cs

public void ConfigureServices(IServiceCollection services)

{

    services.AddRazorPages();

}

 

// In a Razor Page (Index.cshtml)

@page

@model IndexModel

<h2>Welcome to Razor Pages</h2>

 

// In the corresponding Page Model (Index.cshtml.cs)

public class IndexModel : PageModel

{

    public void OnGet()

    {

        // Handle GET requests

    }

}

74.  How do you implement rate limiting in a .NET Core Web API using middleware?
Answer: Rate limiting in a .NET Core Web API can be implemented using middleware to control the number of requests a client can make within a specified time period.

Example:

public class RateLimitingMiddleware

{

    private readonly RequestDelegate _next;

    private readonly Dictionary<string, int> _requests = new Dictionary<string, int>();

 

    public RateLimitingMiddleware(RequestDelegate next)

    {

        _next = next;

    }

 

    public async Task InvokeAsync(HttpContext context)

    {

        var clientIp = context.Connection.RemoteIpAddress?.ToString();

        if (clientIp == null)

        {

            context.Response.StatusCode = StatusCodes.Status400BadRequest;

            await context.Response.WriteAsync("Unable to determine client IP.");

            return;

        }

 

        if (!_requests.ContainsKey(clientIp))

        {

            _requests[clientIp] = 0;

        }

 

        if (_requests[clientIp] >= 100) // Example limit of 100 requests

        {

            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;

            await context.Response.WriteAsync("Rate limit exceeded.");

            return;

        }

 

        _requests[clientIp]++;

        await _next(context);

        _requests[clientIp]--; // Decrement the request count after processing

    }

}

 

// In Startup.cs

public void Configure(IApplicationBuilder app)

{

    app.UseMiddleware<RateLimitingMiddleware>();

    // Other middleware

}

75.  How do you implement global exception handling in .NET Core?
Answer: Global exception handling in .NET Core can be implemented using middleware to catch and log exceptions, and return appropriate responses to the client.

Example:

public class ExceptionHandlingMiddleware

{

    private readonly RequestDelegate _next;

    private readonly ILogger<ExceptionHandlingMiddleware> _logger;

 

    public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)

    {

        _next = next;

        _logger = logger;

    }

 

    public async Task InvokeAsync(HttpContext context)

    {

        try

        {

            await _next(context);

        }

        catch (Exception ex)

        {

            _logger.LogError(ex, "An unhandled exception occurred.");

            context.Response.StatusCode = StatusCodes.Status500InternalServerError;

            await context.Response.WriteAsync("An unexpected error occurred. Please try again later.");

        }

    }

}

 

// In Startup.cs

public void Configure(IApplicationBuilder app)

{

    app.UseMiddleware<ExceptionHandlingMiddleware>();

    // Other middleware

}



Comments

Popular posts from this blog

Tailwind CSS - Crash Course

Swift In Depth - Interview Questions