Here are 50 intermediate level questions about .NET Core with answers and examples:
- What are the key differences between .NET Framework and .NET Core?
Both .NET Framework and .NET Core are platforms for building software applications. .NET Framework has been around longer, and is Windows-only. .NET Core is a newer, open-source version of .NET that runs on Windows, Linux, and macOS. Key differences include:
- Cross-platform: .NET Core works across different platforms (Windows, Linux, macOS), whereas .NET Framework is Windows-specific.
- Performance: .NET Core has been designed to have a smaller footprint and is optimized for high-performance scenarios such as microservices.
- App models: .NET Core supports more application types, including console apps, ASP.NET Core web apps, Universal Windows Platform (UWP) apps, and more.
- What are Middlewares in ASP.NET Core? Middleware components handle requests and responses in an ASP.NET Core application. They form a pipeline through which every request must travel. Middlewares are used for tasks like exception handling, authentication, and serving static files. For example, to add a middleware that handles exceptions:
public void Configure(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); // ... }
- How do you handle Exceptions globally in ASP.NET Core?
You can handle exceptions globally in ASP.NET Core by using middleware. For example, you can use theUseExceptionHandler
middleware:
public void Configure(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); // ... }
This will redirect to the Error action in the Home controller whenever an exception is thrown.
- How do you implement Dependency Injection in ASP.NET Core?
ASP.NET Core has built-in support for Dependency Injection. You can register services in theConfigureServices
method ofStartup.cs
, and then these services can be injected into controllers or other services. For example:
public void ConfigureServices(IServiceCollection services) { services.AddTransient<MyService>(); // ... }
Then, you can inject MyService
into a controller:
public class HomeController : Controller { private readonly MyService _myService; public HomeController(MyService myService) { _myService = myService; } }
- What is Entity Framework Core?
Entity Framework Core (EF Core) is an open-source, lightweight, extensible, and cross-platform version of the popular Entity Framework data access technology. EF Core is an Object-Relational Mapping (ORM) framework that simplifies data access by letting you work with relational data using .NET objects. - How do you use Entity Framework Core for database migrations?
EF Core has commands for managing database migrations. First, you add a migration using theAdd-Migration
command:
dotnet ef migrations add InitialCreate
Then, you apply this migration to the database using the Update-Database
command:
dotnet ef database update
- How do you query data using Entity Framework Core?
You can query data using LINQ (Language Integrated Query) with EF Core. For example:
using (var context = new MyDbContext()) { var customers = context.Customers.Where(c => c.City == "London").ToList(); }
- How do you use ASP.NET Core Identity for authentication?
ASP.NET Core Identity is a membership system that adds login functionality to ASP.NET Core apps. You can configure it inStartup.cs
:
public void ConfigureServices(IServiceCollection services) { services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); }
Then, you can decorate controller actions with the [Authorize]
attribute to require a logged-in user.
- How do you implement authorization in ASP.NET Core?
Authorization in ASP.NET Core is typically done using the[Authorize]
attribute on controllers or action methods. You can also create custom authorization policies. For example, to require a user to be in the “Admin” role:
[Authorize(Roles = "Admin")] public class AdminController : Controller { // ... }
- What are Tag Helpers in ASP.NET Core?
Tag Helpers in ASP.NET Core are server-side components that render HTML tags. They can be used to create reusable UI components and to simplify the HTML in Razor views. For example, aform
tag helper can simplify the creation of a form:
<form asp-controller="Home" asp-action="Index"> <!-- ... --> </form>
- How do you customize routing in ASP.NET Core?
Routing in ASP.NET Core is configured in theConfigure
method ofStartup.cs
. You can define a custom route by calling theMapRoute
method:
app.UseMvc(routes => { routes.MapRoute( name: "custom", template: "{controller=Home}/{action=Index}/{id?}"); });
- What is Dependency Injection and how is it implemented in .NET Core?
Dependency Injection (DI) is a design pattern in which an object’s dependencies are supplied by other objects. It’s implemented in .NET Core through the built-in IoC (Inversion of Control) container. For example, you can add a service to the DI container inStartup.cs
:
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<MyService>(); }
Then, MyService
can be injected into a controller or another service.
- What is the Kestrel web server in .NET Core?
Kestrel is a cross-platform web server for ASP.NET Core. It’s the default web server and is included with .NET Core. It’s designed to be fast and can be used as an edge server (i.e., it can be exposed directly to the Internet) or with a reverse proxy. - How do you implement logging in ASP.NET Core?
ASP.NET Core includes a logging API that works with a variety of built-in and third-party logging providers. You can use it by injectingILogger<T>
into your classes:
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } }
Then, you can log messages using the _logger
object.
- How do you read configuration values in .NET Core?
In .NET Core, configuration values can be read using theIConfiguration
service. This can be injected into your classes, and then you can use theGetValue
orGetSection
methods to read configuration values.
public class MyService { private readonly IConfiguration _configuration; public MyService(IConfiguration configuration) { _configuration = configuration; } public void DoSomething() { var setting = _configuration.GetValue<string>("MySetting"); // ... } }
- How to use the Repository pattern in Entity Framework Core?
The Repository pattern is a way to encapsulate data access code. In EF Core, a repository is usually a class that takes aDbContext
in its constructor. Here’s an example of a repository that handles operations forCustomer
entities:
public class CustomerRepository { private readonly MyDbContext _context; public CustomerRepository(MyDbContext context) { _context = context; } public IEnumerable<Customer> GetAll() { return _context.Customers.ToList(); } // ... }
- What is ASP.NET Core SignalR?
SignalR is a library that simplifies adding real-time web functionality to apps. Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available. - What are some use cases for SignalR?
Some use cases for SignalR include:
- Chat applications
- Real-time dashboards and monitoring
- Collaborative apps (e.g., real-time drawing, shared whiteboard)
- What is a .NET Core Worker Service?
A Worker Service in .NET Core is a type of project that’s designed for long-running tasks. It’s a good choice for microservices, and for tasks like background jobs, health checks, or batch processing. - How do you host a .NET Core application?
You can host a .NET Core application in a variety of ways:
- Using Kestrel directly
- Behind a reverse proxy, such as IIS, Nginx, or Apache
- In a Docker container
- In the cloud, for example on Azure, AWS, or Google Cloud The choice of hosting depends on the specific requirements of your application.
- How do you handle sessions in ASP.NET Core?
ASP.NET Core provides middleware for managing sessions. First, you need to add the session middleware inStartup.cs
:
services.AddSession();
And in the Configure
method:
app.UseSession();
Then, you can access the session in your controllers or views using HttpContext.Session
.
- What is a Middleware Pipeline in ASP.NET Core?
The middleware pipeline in ASP.NET Core is the sequence of middleware components that handle a request and produce a response. Each middleware in the pipeline is responsible for invoking the next middleware, or short-circuiting the pipeline if appropriate. You can define the middleware pipeline in theConfigure
method ofStartup.cs
. - How do you create a Web API in ASP.NET Core?
A Web API in ASP.NET Core is created just like any other controller, but it returns data rather than views. You can create an API controller by deriving fromControllerBase
and using the[ApiController]
attribute:
[ApiController] [Route("[controller]")] public class MyApiController : ControllerBase { // ... }
- How do you use the
HttpClient
class in .NET Core?
TheHttpClient
class is used for sending HTTP requests and receiving HTTP responses. It’s recommended to useHttpClient
throughIHttpClientFactory
, which can be injected into your classes. For example:
public class MyService { private readonly HttpClient _httpClient; public MyService(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient(); } public async Task<string> GetAsync(string url) { var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } }
- What are Razor Pages in ASP.NET Core?
Razor Pages is a feature of ASP.NET Core that makes coding page-focused scenarios easier and more productive. Razor Pages are similar to MVC, but they’re more suitable for pages that handle simple actions and don’t need a full controller. - What is View Component in ASP.NET Core?
View Components in ASP.NET Core are similar to partial views, but they’re more powerful. They can have their logic and can be reused across views. View Components consist of a C# class derived fromViewComponent
and a Razor view. For example, a View Component might look like this:
public class MyViewComponent : ViewComponent { public IViewComponentResult Invoke() { var model = new MyModel(); // ...populate the model... return View(model); } }
- What is the role of the
Program.cs
file in a .NET Core application?
TheProgram.cs
file in a .NET Core application is the entry point of the application. It typically contains code to create a host, configure services, and start the application. - How can you secure an ASP.NET Core Web API?
There are several ways to secure an ASP.NET Core Web API:
- Using JWT (JSON Web Tokens) for authentication
- Using API keys
- Using OAuth or OpenID Connect if the API is part of an application that has a user interface Regardless of the method, it typically involves validating the credentials in middleware and then setting the user context.
- What is the
IWebHostEnvironment
interface in ASP.NET Core?
TheIWebHostEnvironment
interface provides information about the web hosting environment an application is running in. It can be used to get the environment name (like Development, Staging, Production), and paths to find the content files, and so on.
public class Startup { public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } // ... }
- What are some ways to improve the performance of a .NET Core application?
Some ways to improve the performance of a .NET Core application include:
- Using the latest version of .NET Core, as performance improvements are made in each release.
- Reducing memory allocations, for example by using the
ArrayPool
class or by avoiding LINQ. - Optimizing data access, for example by using async methods, batching queries, or caching results.
- Using performance profiling tools to identify bottlenecks.
- What is Swagger and how is it used with ASP.NET Core Web API?
Swagger, also known as OpenAPI, is a specification for documenting REST APIs. It includes information about the API’s endpoints, request/response types, authentication, and more. You can use the Swashbuckle library to add Swagger to an ASP.NET Core Web API. It generates a Swagger JSON document that can be viewed with a Swagger UI, which provides an interactive documentation of your API.
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(); // ... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); // ... }
- What is the use of
IOptions
in .NET Core?IOptions
is used to access the configuration settings of an application. It’s typically used with strongly-typed settings, i.e., settings that are represented by a class. For example, if you have aMySettings
class, you can add it to the DI container inStartup.cs
like this:
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
Then, you can access the settings in your services like this:
public class MyService { private readonly MySettings _settings; public MyService(IOptions<MySettings> options) { _settings = options.Value; } // ... }
- What is Dependency Injection (DI) and how is it implemented in .NET Core?
Dependency Injection (DI) is a design pattern that allows a class to receive its dependencies from an external source rather than creating them itself. This promotes loose coupling and increases testability. .NET Core has built-in support for DI. You can register your services in theConfigureServices
method inStartup.cs
, and then they will be available for constructor injection in your controllers, Razor Pages, etc.
public void ConfigureServices(IServiceCollection services) { services.AddTransient<MyService>(); // ... }
- How do you use AutoMapper in .NET Core?
AutoMapper is a library that simplifies mapping between objects, which is often useful when mapping between domain models and view models. You can use AutoMapper in .NET Core by first installing theAutoMapper.Extensions.Microsoft.DependencyInjection
NuGet package. Then, you can add AutoMapper to the DI container:
services.AddAutoMapper(typeof(Startup));
Then, you create a profile to define the mappings:
public class MyProfile : Profile { public MyProfile() { CreateMap<MyDomainModel, MyViewModel>(); } }
Finally, you can use the IMapper
interface in your services to perform mappings:
public class MyService { private readonly IMapper _mapper; public MyService(IMapper mapper) { _mapper = mapper; } public MyViewModel GetViewModel() { var model = new MyDomainModel(); // ...populate the model... return _mapper.Map<MyViewModel>(model); } }
- What is a
Task
in .NET Core?
ATask
in .NET Core represents an asynchronous operation. It’s similar to aFuture
orPromise
in other programming languages. You can use theasync
andawait
keywords to work with tasks in a non-blocking way.
public async Task<string> GetWebPageAsync(string url) { using var httpClient = new HttpClient(); return await httpClient.GetStringAsync(url); }
- What is ASP.NET Core Identity?
ASP.NET Core Identity is a membership system that adds login functionality to ASP.NET Core applications. It supports user registration, two-factor authentication, account confirmation, password recovery, and more. - What is EF Core Migrations and how to use it?
EF Core Migrations is a feature that allows you to manage changes to your database schema. You can use migrations to create or drop tables, add or remove columns, create indices, and more. To add a migration, you can use theAdd-Migration
command in the Package Manager Console, ordotnet ef migrations add
in the command line. This will create a new migration class where you can define the changes. To apply the migrations to the database, you can use theUpdate-Database
command in the Package Manager Console, ordotnet ef database update
in the command line. - How do you handle exceptions globally in ASP.NET Core?
In ASP.NET Core, you can use middleware to handle exceptions globally. TheUseExceptionHandler
middleware can catch exceptions and redirect to an error page:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } // ... }
In this example, if the application is running in the Development environment, it will display the detailed error page. Otherwise, it will redirect to the /Error
page.
- What is Serilog and how do you use it in .NET Core?
Serilog is a logging library for .NET. It supports structured logging, which means that instead of logging strings, you’re logging event data. This makes it easier to search, analyze, and visualize logs. To use Serilog in .NET Core, first install theSerilog.AspNetCore
NuGet package. Then, you can configure Serilog in theProgram.cs
file:
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); try { Log.Information("Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }
This will configure Serilog to write logs to the console. You can also write logs to files, databases, or other outputs by using different sinks.
- What is the difference between
AddSingleton
,AddScoped
, andAddTransient
in .NET Core?AddSingleton
,AddScoped
, andAddTransient
are methods used to register services with the DI container in .NET Core. They differ in the lifetime of the services:
AddSingleton
creates a single instance of the service for the entire application.AddScoped
creates a new instance for each request.AddTransient
creates a new instance every time the service is requested.
- How do you validate a model in ASP.NET Core?
In ASP.NET Core, you can validate models using Data Annotations. You add attributes to the properties of your model to specify the validation rules:
public class MyModel { [Required] [StringLength(100)] public string Name { get; set; } }
Then, in your action methods, you can
check the ModelState.IsValid
property to see if the model is valid:
public IActionResult Post([FromBody] MyModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // ...process the model... }
- What is Kestrel server in .NET Core?
Kestrel is a cross-platform web server for ASP.NET Core. It’s the default web server and can be used directly as an edge server processing requests from the Internet, or it can be used behind a reverse proxy like Nginx or IIS. - How do you implement JWT authentication in ASP.NET Core?
JWT (JSON Web Tokens) authentication can be implemented in ASP.NET Core by using theMicrosoft.AspNetCore.Authentication.JwtBearer
NuGet package. First, you need to add the JWT bearer authentication service in theConfigureServices
method:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; });
Then, in the Configure
method, you need to use the authentication middleware:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseAuthentication(); app.UseAuthorization(); // ... }
Now, you can protect your actions or controllers using the [Authorize]
attribute.
- How do you consume a RESTful API in .NET Core?
You can consume a RESTful API in .NET Core by using theHttpClient
class:
public async Task<string> GetWebPageAsync(string url) { using var httpClient = new HttpClient(); return await httpClient.GetStringAsync(url); }
You can also use libraries like RestSharp or Flurl that provide a more high-level API for consuming RESTful services.
- What are the different types of configurations available in .NET Core?
.NET Core provides various ways to handle configurations:
- appsettings.json: This is a JSON file where you can put your application’s configuration settings.
- Environment Variables: You can set environment variables at the operating system level, and .NET Core can access these values.
- Command Line Arguments: You can pass configurations when starting your application by providing them as command-line arguments.
- User Secrets: This is used to store sensitive data during development. User secrets are stored outside of the project tree to avoid the accidental sharing of sensitive data.
- Azure Key Vault: For Azure-hosted applications, Azure Key Vault is a secure way to manage and store secrets. The configuration sources are read in the order above, with later sources overwriting values from earlier sources.
- What are Tag Helpers in ASP.NET Core?
Tag Helpers in ASP.NET Core are a new way to define server-rendered HTML elements. They enable server-side code to participate in creating and rendering HTML elements in Razor files. They are similar to HTML Helpers but have a more HTML-like syntax. For example, theform
tag helper can be used to create a form that posts back to a specific action method:
<form asp-controller="Home" asp-action="Index" method="post"> <!-- form fields --> </form>
- What is the role of
wwwroot
directory in an ASP.NET Core project?
Thewwwroot
folder in an ASP.NET Core project is the web root of your application. It’s the root directory from which static files will be served, such as CSS, JavaScript, and images. - What are the differences between .NET Core and .NET Framework? .NET Core and .NET Framework are both platforms for building applications on the .NET platform, but they have some important differences:
- Cross-platform: .NET Core is cross-platform, meaning it can run on Windows, macOS, and Linux, while .NET Framework runs only on Windows.
- Open-source: .NET Core is open-source and community-driven, while .NET Framework is not.
- Side-by-side installation: .NET Core supports side-by-side installation of different versions of the runtime on the same machine. This is not possible with .NET Framework.
- APIs: .NET Core has a smaller API surface compared to .NET Framework, but with .NET Standard, a large number of APIs are available to both.
- Performance: .NET Core has been designed to have better performance than .NET Framework.
- Project structure: .NET Core uses a simplified project file (
.csproj
) format compared to .NET Framework. - Tools and libraries: Some .NET Framework technologies, such as WebForms, WCF, and Workflow, are not available in .NET Core.
- How do you implement logging in .NET Core?
.NET Core has built-in support for logging APIs that are simple, flexible, and pluggable. The built-inILogger
interface can be used for logging. You can use it in your classes by asking the DI container to provide it through the constructor:
public class MyService { private readonly ILogger<MyService> _logger; public MyService(ILogger<MyService> logger) { _logger = logger; } public void DoSomething() { _logger.LogInformation("Doing something"); } }
You can configure the logging providers (where the logs are sent to) in the Program.cs
file:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
In this example, the logs are written to the console. There are also providers for other destinations, such as files, Azure Log Analytics, etc.
- What is Razor Pages in ASP.NET Core?
Razor Pages is a feature of ASP.NET Core that makes coding page-focused scenarios easier and more productive. With Razor Pages, each web page is a self-contained unit of code and markup which can be more convenient for simpler scenarios like forms. A Razor Page looks very much like an MVC View but has a corresponding Page Model file where you can write your server-side code. It’s an alternative to the MVC pattern for building web UI in ASP.NET Core.
RELATED POSTS
View all