.NET Core Interview Questions

As a .NET developer, I have been in many interviews at companies like Microsoft, Deloitte, and others from Forbes 500. A big part of the interviews was about data structures and algorithms. I also received many .NET Core and ASP.NET questions.

I will try to give you the questions that appear the most in the interviews.

What is SOLID?

The SOLID principles are a set of guidelines for object-oriented programming. These principles are intended to make software designs more understandable, flexible, and maintainable.

SOLID stands for:

  • Single responsibility. This means that a class should do only one thing. Forget about classes that have thousands of lines.
  • Open-close. The open-close principle means a class should be open for extensions but closed for modifications.
  • Liskov substitution. Objects should be replaceable with instances of their subtypes without altering the correctness of the program. So use the interfaces instead of classes.
  • Interface segregation. Some specialized interfaces are better than a general interface. Nobody should implement methods of an interface that they don’t need.
  • Dependency Inversion Principle

What represents DRY?

DRY is a programming principle that stands for Don’t Repeat Yourself. This means that you don’t write the same code twice. Whenever you need to write the same code, you extract that section into a method or even a class.

How do you write a middleware?

You must have a method called Invoke or InvokeAsync. Also, your middleware can receive the delegate for the next middleware in the pipeline.

public class ExampleMiddleware
{
    private readonly RequestDelegate _nextMiddleware;

    public RequestCultureMiddleware(RequestDelegate nextMiddleware)
    {
        _nextMiddleware = nextMiddleware;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        //here you can access the request body/headers/cookies/url etc.
        await _nextMiddleware(context); // call the next middleware
    }
}

What’s the difference between calling a middleware with the methods app.Use and app.Run?

The Usemethod receives a delegate parameter that represents the next middleware in the pipeline. A Run delegate is a terminal middleware because it doesn’t receive a reference to the next middleware.

app.Use(async (context, next) =>
{
    await next.Invoke(); //calling the next middleware in the pipeline
});

app.Run(async context =>
{
    await context.Response.WriteAsync("Here the pipeline ends. Now it goes back!");
});

What’s the difference between middleware and filters in ASP.NET Core?

A middleware will perform tasks before and after a request is processed while the filter is executed on the request processing pipeline.

Middlewares can run on all requests, while filters only execute on particular controllers or actions.

Middlewares operates only on HttpContext, while filters have access to MVC or Razor page objects like ModelState.

What are the advantages of .NET Core over .NET Framework?

  • .NET Core is cross-platform. It runs on Windows, Linux, and macOS. It can be used very easily for cloud environments.
  • It’s built from scratch and much faster than the older .NET Framework. Dotnet Core is more lightweight and modular than the .NET framework.
  • It’s free and open-source. Anyone can make improvements to the repository.

What is NuGet?

Nuget is a package manager for .NET projects. It can be used to add third-party libraries and frameworks to your project. You can use NuGet to keep your libraries up-to-date. For frontend libraries, you should use package managers like npm or yarn.

When to choose Parallel.For instead of async and await?

The Parallel class is designed for parallelism. It should be used for heavy CPU processing tasks that can be executed in parallel. For example, usually, image processing tasks can be implemented in parallel.

On the other hand, async and await keywords are designed for tasks that must wait for previous tasks to be done. For example, you want to write the source code of a website in a text file. Both operations are blocking the current thread until it finishes.

You can read more about the Parallel class in this article.

In ASP.NET Core, what are the names of the services based on their lifetime?

In ASP.NET Core, we have three types of services:

  1. Singleton
  2. Scoped
  3. Transient

What’s the difference between a scoped and a transient service?

A scoped service is the same within a request. For example, the same instance is provided if a service is injected inside another service and a controller.

A transient service means a new instance is provided every time the service is injected.

Why do we use dependency injection?

Dependency injection allows you to separate the creation of an object from its use. This allows us to inject different instances into different situations. For example, you have a class with a database connection object injected. If you want to write unit tests for that class, you probably don’t want actually to call the database. So, you can inject a different instance that mocks your database.

Using dependency injection, you avoid writing the same code that instantiates an object. Your classes will look cleaner.

What’s the difference between Required and BindRequired attributes?

Required only works for reference types. In the case of value, variable types Required don’t work because the variables get the default value.

For example, in the case of Integer variables, the default value is zero(0).

This is why you should use the BindRequired attribute for value variable type to ensure that a parameter is bound.

You can read more about Required and BindRequired attributes in my article.

Which route does have priority: the attribute route or the conventional route?

The attribute route has priority.

What’s the difference between GET and POST methods?

  • A GET method is less secure because parameters are sent directly to the URL
  • A GET action can be cached and bookmarked. POST actions cannot be cached or bookmarked.
  • A GET can only send ASCII characters. In the case of a POST, you don’t have limitations; you can send binary, strings, and special characters.
  • Web Browser usually accepts URLs with a maximum of 255 characters. A body of a POST method is limited only by the servers. So, you can send fewer data on GET actions instead of POST.
  • GET methods are used to request data. On the other hand, POST methods are used to save or send information and perform actions requiring the parameters to be hidden, like a login page.

What is Kestrel, and why do we need it?

Kestrel is an open-source web server. Instead of IIS, Kestrel is cross-platform, so ASP.NET Core will work on any operating system that .NET Core supports.

Kestrel can be used in conjunction with IIS, but because IIS is not cross-platform, it will only work for Windows. That’s why we need Kestrel for ASP.NET Core to be cross-platform.

In case we use a reverse proxy like IIS or Nginx, then the Kestrel server should be placed after in the request pipeline.

What’s the difference between Razor Pages and MVC?

Razor Pages use the MVVM(Model-View-ViewModel) pattern, and MVC uses Model View Controller. Razor pages use page-based routing, while MVC uses controllers to manage requests.

Why is recommended to pass the data to a ViewModel when we are rendering a view?

We pass a view model instead of a model because usually, we don’t want to expose the entire object, or maybe the view needs properties of a couple of objects. So instead of passing unnecessary data, we give an object that contains only the required data.

How do you keep the configuration for each environment in the application settings file?

App settings file can have the environment in the file name: appsettings.Development.json.

What’s the difference between the JSON method and the Content method?

Json returns the correct MIME type for JSON, whereas Content does not.

What type of HTTP verbs do you know?

The HTTP verbs are GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.

When do you use PUT and when do PATCH?

We do use PUT when the client sends the entire object. The PATCH method is used when the client sends only partial data.

What is OWIN?

OWIN stands for Open Web Interface for .NET. It describes how web applications and servers should be decoupled to move to other environments quickly.

What’s the difference between Dispose and Finalize methods?

Finalize method is called by Garbage Collector whenever it thinks it’s necessary. So you don’t know when this will happen. The Dispose method should be called from your code instead. Dispose is used to close and clean unmanaged resources like database connections, file handlers, and HTTP connections.

Name three advantages of Microservice architecture

  1. The microservice can be written in any programming language.
  2. Different teams can work on other parts of the project. Each group can choose its desired programming language for development.
  3. Microservice architecture can be easily scaled. In the case of a monolith application, you must scale the whole application. In a microservice architecture, you can scale only some services. There are tools like Kubernetes that orchestrate the containers of the services.
  4. You can update the service easily compared to a monolith application.
  5. Errors are isolated. If a microservice has an error, the error is separated from the other services. For example, let’s assume you have an online store and the checkout service has an error. The login service will still work because it doesn’t interfere with that service.

Why do we use Docker containers?

Docker containers are a secure way to build and ship isolated units. Containers enable programmers to work with the same libraries and configurations across multiple environments. As a programmer, using a Docker container, you don’t worry about the operating system or machine configuration.

Also, using an orchestrator, you can manage the resource between containers.

How do you protect against a CSRF attack?

To protect against a CSRF attack, we generate an anti-forgery token, and we validate this token on the server side using [ValidateAntiForgeryToken].

What does state management in ASP.NET Core mean?

The HTTP protocol doesn’t store the user’s data between requests. This means that the ASP.NET Core framework should provide a way to store the data between requests.

In ASP.NET Core, what are the available options for keeping the state between requests?

In ASP.NET Core, you can use for keeping the state one of the following storages:

  1. Cookies
  2. TempData
  3. Cache
  4. Session state
  5. Hidden Fields
  6. Query strings
  7. HttpContext items

How do we handle file upload in ASP.NET Core?

In ASP.NET Core, we handle file upload using the IFormFile interface:

public IActionResult ProfilePhoto(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return BadRequest("File not uploaded");
    }

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

    using (var stream = new FileStream(path, FileMode.Create))
    {
        file.CopyTo(stream);
    }

    return RedirectToAction("Index");
}

How do sessions works in ASP.NET?

When a user visits for the first time the website, a session id is generated and stored in the user’s cookies. When the user returns to the website, ASP.NET retrieves this cookie and gets the session’s stored values.

What is a Health Check, and how do you configure one in ASP.NET Core?

A health check solution provides a way for the application users to check that the service works.

A simple health check can be implemented by adding the following service:

_services.AddHealthChecks();

You also implement the health check middleware in the pipeline:

app.MapHealthChecks("/health");

If the service is unavailable, you will get an HTTP response status code 503 Service unavailable.

How do you configure Logging in ASP.NET Core applications?

In ASP.NET Core applications, you can use Microsoft.Extensions.Logging package. Using the ILogger interface, you can log messages.

using Microsoft.Extensions.Logging;

class MyClass
{
    private readonly ILogger<MyClass> _logger;

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

    public void DoWork()
    {
        try
        {
            // Do some stuff
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while executing code.");
        }
    }
}

For the logging configuration, you should use the ILoggerFactory interface:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    // Configure logging
    loggerFactory.AddConsole();
    loggerFactory.AddDebug();
    // Add other logging providers as needed
    // ---
}

Also, you can use popular libraries like NLog or Serilog.

Name three ways of running background tasks in ASP.NET Core

  1. Using a library like HangFire
  2. Using hosted services. For this, you should implement the IHostedService. This method defines two methods:
    • StartAsync
    • StopAsync
  3. Using Task.Run method
  4. Using BackgroundWorker class

What are the different type’s results that you can return from an action in ASP.NET Core?

In the ASP.NET controller’s action, you can return:

  • ViewResult – returns a view, which is a Razor template that is used to render HTML
  • ContentResult – returns a string of content, typically used for returning plain text or HTML
  • JsonResult – returns a JSON-formatted object, which can be used to return data to a client-side script
  • FileResult – returns a file, such as a PDF, text file, or image
  • RedirectResult – redirects the client to a different URL
  • RedirectToActionResult – redirects the client to a different action method within the same controller
  • RedirectToRouteResult – redirects the client to a different route
  • StatusCodeResult – returns a specific HTTP status code, such as 404 (Not Found) or 500 (Internal Server Error)
  • ObjectResult – returns an object
  • EmptyResult – returns an empty result

What is OWASP?

OWASP stands for Open Web Application Security Project. OWASP TOP 10 lists the most frequent threats to web applications.

Leave a Comment