Dotnet Core Interview Questions And Answers

Question  1. What is .NET Core?

Answer: The .NET Core platform is a new .NET stack that is optimized for open source development and agile delivery on NuGet.

.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the ASP.NET Core package.

.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.

Question  2. What is ASP.NET Core?

Answer: ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core is completely rewriting that work with the .net Core framework. It is much faster, configurable, modular, scalable, extensible and cross-platform support. It can work with both .NET Core and .net framework via the .NET standard framework. It is best suitable for developing cloud-based applications such as web application, mobile application, IoT application.

Question  3. What are the features provided by ASP.NET Core?

Answer: Following are the core features that are provided by the ASP.NET Core

  • Built-in supports for Dependency Injection
  • Built-in supports for the logging framework and it can be extensible
  • Introduced new, fast and cross-platform web server – Kestrel. So, a web application can run without IIS, Apache, and Nginx.
  • Multiple hosting ways are supported
  • It supports modularity, so the developer needs to include the module required by the application. However, .NET Core framework is also providing the meta package that includes the libraries
  • Command-line supports to create, build and run the application
  • There is no web.config file. We can store the custom configuration into an appsettings.json file
  • There is no Global.asax file. We can now register and use the services into startup class
  • It has good support for asynchronous programming
  • Support WebSocket and SignalR
  • Provide protection against CSRF (Cross-Site Request Forgery)

Question  4. What are the advantages of ASP.NET Core over ASP.NET?

Answer: There are following advantages of ASP.NET Core over ASP.NET :

  • It is cross-platform, so it can be run on Windows, Linux, and Mac.
  • There is no dependency on framework installation because all the required dependencies are ship with our application
  • ASP.NET Core can handle more request than the ASP.NET
  • Multiple deployment options available withASP.NET Core

Question  5. Can ASP.NET Core work with the .NET framework?

Answer: Yes. This might surprise many, but ASP.NET Core works with .NET framework and this is officially supported by Microsoft.

ASP.NET Core works with:

  • .NET Core framework
  • .NET framework

Question  6. What are some characteristics of .NET Core?

Answer:

  • Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.
  • Cross-platform: Runs on Windows, macOS and Linux; can be ported to other OSes. The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
  • Command-line tools: All product scenarios can be exercised at the command-line.
  • Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
  • Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.
  • Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support

Question  7. What is CTS?

Answer: The Common Type System (CTS) standardizes the data types of all programming languages using .NET under the umbrella of .NET to a common data type for easy and smooth communication among these .NET languages.

CTS is designed as a singly rooted object hierarchy with System.Object as the base type from which all other types are derived.

CTS supports two different kinds of types:

  • Value Types: Contain the values that need to be stored directly on the stack or allocated inline in a structure. They can be built-in (standard primitive types), user-defined (defined in source code) or enumerations (sets of enumerated values that are represented by labels but stored as a numeric type).
  • Reference Types: Store a reference to the value‘s memory address and are allocated on the heap. Reference types can be any of the pointer types, interface types or self-describing types (arrays and class types such as user-defined classes, boxed value types and delegates).

Question  8. What is the difference between .NET Core and Mono?

Answer: Mono is third party implementation of .Net Framework for Linux/Android/iOs

.Net Core is Microsoft’s own implementation for the same.

Question  9. What’s the difference between SDK and Runtime in .NET Core?

Answer: The SDK is all of the stuff that is needed/makes developing a .NET Core application easier, such as the CLI and a compiler.

The runtime is the “virtual machine” that hosts/runs the application and abstracts all the interaction with the base operating system.

Question  10. Explain the difference between Task and Thread in .NET

Answer: Thread represents an actual OS-level thread, with its own stack and kernel resources. Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread, you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture. ThreadPool is a wrapper around a pool of threads maintained by the CLR.

The Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool. Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result.

Question  11. Explain what is included in .NET Core?

Answer: A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interop and other basic services.

A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.

A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.

The ‘dotnet’ app host, which is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.

Question  12. What are the benefits of explicit compilation?

Answer: Ahead of time (AOT) delivers faster start-up time, especially in large applications where much code executes on startup. But it requires more disk space and more memory/virtual address space to keep both the IL and precompiled images. In this case the JIT Compiler has to do a lot of disk I/O actions, which are quite expensive.

Question  13. What is CoreCLR?

Answer: CoreCLR is the .NET execution engine in .NET Core, performing functions such as garbage collection and compilation to machine code.

Consider:

Question  14. What is a JIT compiler?

Answer: Before a computer can execute the source code, special programs called compilers must rewrite it into machine instructions, also known as object code. This process (commonly referred to simply as “compilation”) can be done explicitly or implicitly.

Implicit compilation is a two-step process:

  • The first step is converting the source code to intermediate language (IL) by a language-specific compiler.
  • The second step is converting the IL to machine instructions. The main difference with the explicit compilers is that only executed fragments of IL code are compiled into machine instructions, at runtime. The .NET framework calls this compiler the JIT (Just-In-Time) compiler.

Question  15. What is Kestrel?

Answer:

  • Kestrel is a cross-platform web server built for ASP.NET Core based on libuv – a cross-platform asynchronous I/O library.
  • It is a default web server pick since it is used in all ASP.NET Core templates.
  • It is really fast.
  • It is secure and good enough to use it without a reverse proxy server. However, it is still recommended that you use IIS, Nginx or Apache or something else.

You can set a kestrel server in the program.cs file:

public static void Main(string[] args)

{

      var host = new WebHostBuilder()

      .UseContentRoot(Directory.GetCurrentDirectory())

      .UseKestrel()

      .UseIISIntegration()

      .UseStartup<Startup>()

      .ConfigureKestrel((context, options) =>

      {

            // Set properties and call methods on options

      })

      .Build();

      host.Run();

}

Question  16. What is WebListener?

Answer: ASP.NET Core ships two server implementations Kestrel and WebListener. WebListener is also a web server for ASP.NET Core that runs only on Windows. It’s built on the Http.Sys kernel mode driver. WebListener is an alternative to Kestrel that can be used for direct connection to the Internet without relying on IIS as a reverse proxy server.

Question  17. What is the difference between .NET Core and .NET Framework?

Answer: .NET as whole now has 2 flavors:

  1. .NET Framework
  2. .NET Core

.NET Core and the .NET Framework have (for the most part) a subset-superset relationship. .NET Core is named “Core” since it contains the core features from the .NET Framework, for both the runtime and framework libraries. For example, .NET Core and the .NET Framework share the GC, the JIT and types such as String and List.

.NET Core was created so that .NET could be open source, cross platform and be used in more resource-constrained environments.

Question  18. What’s the difference between .NET Core, .NET Framework, and Xamarin?

Answer:

  • .NET Framework is the “full” or “traditional” flavor of .NET that’s distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.
  • .NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.
  • Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices.

Xamarin usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.

Question  19. When should we use .NET Core and .NET Standard Class Library project types?

Answer:

  • Use a .NET Standard library when you want to increase the number of apps that will be compatible with your library, and you are okay with a decrease in the .NET API surface area your library can access.
  • Use a .NET Core library when you want to increase the .NET API surface area your library can access, and you are okay with allowing only .NET Core apps to be compatible with your library.

Question  20. What is the difference between AppDomain, Assembly, Process, and a Thread?

Answer: An AppDomain is an isolation unit within a process. AppDomains can be created at runtime, loaded with code, and unloaded. It’s an isolation boundary designed to make .NET apps more reliable.

An assembly holds one or more modules, which hold compiled chunks of code. You will typically see an assembly as an .EXE or a .DLL.

A process is an executing application. A process, in the simplest terms, is an executing program. One or more threads run in the context of the process. A process can create other processes which are known as Child Processes. Process takes more time to terminate and it is isolated means it does not share memory with any other process.

A thread is an execution context. The operating system executes code within a thread. The operating system switches between threads, allowing each to execute in turn, thus giving the impression that multiple applications are running at the same time.

Question  21. What’s the difference between RyuJIT and Roslyn?

Answer: Roslyn is a compiler that takes your source code and generates IL bytecode. (Roslyn is the compiler that compiles your code (C# or VB) to IL). Roslyn API is what you need if you want to play with syntax tree, compilation, and semantic model.

RyuJIT is a Just In Time compiler that compiles your IL to native code. RyuJIT doesn’t have a public API.

            RyuJIT takes said bytecode, at runtime, and generates native code. You can embed Roslyn into an app to compile source code on the fly, but RyuJIT is strictly for the runtime and cannot be accessed as far as I know.

Explain Finalize vs Dispose usage?

Question  22. How many types of JIT Compilations do you know?

Answer: There are 3 types of compilers.

Pre-JIT:

Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

Econo-JIT:

This compiler compiles only MSIL code of those methods that are called at Runtime. However, these compiled methods are removed when they are not required.

Normal-JIT:

Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.

What is the equivalent of WebForms in ASP.NET Core?

Question  23. What is Metapackages?

Answer: The framework .NET Core 2.0 introduced Metapackage that includes all the supported packages by ASP.NET code with their dependencies into one package. It helps us to do fast development as we don’t require to include the individual ASP.NET Core packages. The assembly Microsoft.AspNetCore.All is a meta package provided by ASP.NET core.

Question  24. What is the startup class in ASP.NET core?

   Answer: Startup class is the entry point of the ASP.NET Core application. Every .NET Core application must have this class. This class contains the application configuration rated items. It is not necessary that the class name must be “Startup”, it can be anything, we can configure the startup class in the Program class.

 public class Program

 {

  public static void Main(string[] args)

  {

  CreateWebHostBuilder(args).Build().Run();

  }

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>

  WebHost.CreateDefaultBuilder(args)

  .UseStartup<TestClass>();

 }

Question  25. What is the use of ConfigureServices method of startup class?

Answer: This is an optional method of startup class. It can be used to configure the services that are used by the application. This method calls first when the application is requested for the first time. Using this method, we can add the services to the DI container, so services are available as a dependency in controller constructor.

Question  26. What is the use of the Configure method of startup class?

Answer: It defines how the application will respond to each HTTP request. We can configure the request pipeline by configuring the middleware. It accepts IApplicationBuilder as a parameter and also it has two optional parameters: IHostingEnvironment and ILoggerFactory. Using this method, we can configure built-in middleware such as routing, authentication, session, etc. as well as third-party middleware.

Question  27. What is middleware?

  Answer: It is software which is injected into the application pipeline to handle requests and responses. They are just like chained to each other and form as a pipeline. The incoming requests are passed through this pipeline where all middleware is configured, and middleware can perform some action on the request before passing it to the next middleware. Same as for the responses, they are also passing through the middleware but in reverse order.

Question  28. ASP.NET Core Middleware vs ASP.NET Core Filters?

Answer: Both middleware and filters can serve similar purposes. Choosing between them comes down to whether you need access to the MVC context.

ASP.NET Core Middleware:

The execution of middleware occurs before the MVC context becomes available in the pipeline. That is, middleware does not have access to the ActionExecutedContext or the ActionExecutingContext in the case of an ActionFilter for example. What you do have access to is the HttpContext, which will allow you to perform actions on the request as well as the response. Since model binding hasn’t occurred yet, using middleware would not be suited to running a validation function or modifying values. Middleware will also run on every request regardless of which controller or action is called.

ASP.NET Core Filters:

On the other hand, filters will only run on specified actions and controllers unless you register the filter globally in the startup. Since you have full access to the context you can also access the controller and action itself. Running with the example above using validation, you can run through the full modelstate on the ActionExecutingContext.

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

Answer: We can use both the methods in Configure methods of startup class. Both are used to add a middleware delegate to the application request pipeline. The middleware adds using IApplicationBuilder.Use() may call the next middleware in the pipeline whereas the middleware added using IApplicationBuilder.Run() method never calls the subsequent or next middleware. After the IApplicationBuilder.Run() method, the system stops adding middleware in the request pipeline.

Question  30. What is the use of “Map” extension while adding middleware to the ASP.NET Core pipeline?

Answer: It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path matching. If the request path starts with the given path, middleware on to that branch will execute.

public void Configure(IApplicationBuilder app)

 {

 app.Map(“/path1”, Middleware1);

 app.Map(“/path2”, Middleware2);

 }

Question  31. What is the Run extension?

  Answer: The nature of Run extension is to short circuit the HTTP pipeline immediately. It is a shorthand way of adding middleware to the pipeline that does not call any other middleware which is next to it and immediately returns an HTTP response. So, it’s recommended to use Run extension to hook middleware at last in HTTP pipeline. Let’s see how Run behaves in action.

public void Configure(IApplicationBuilder app)

            {

            app.UseMvc();

            app.Run(async context =>

            {

                        await context.Response.WriteAsync(“Return From Run.”);

            });

            app.Run(async context => {

                        await context.Response.WriteAsync(“This is second Run.”);

            });

            }

we hook two Run functions next to next and while running, we are getting only response from the first Run.

That implies the first run has short circuit the HTTP request and sends response from itself without forwarding to next middleware.

Question  32. What is the Use extension?

Answer: Ref: https://www.codeproject.com/Tips/1069790/Understand-Run-Use-Map-and-MapWhen-to-Hook-Middl-2

There is a chance to pass the next invoker, so that HTTP request will be transferred to the next middleware after execution of current Use if there next invoker is present. In this example, we have attached next invoker with Use extension, so that HTTP call will get transferred to next middleware even we tried to return:

public void Configure(IApplicationBuilder app)

            {

            app.UseMvc();

            app.Use(next=> async context =>

            {

            await context.Response.WriteAsync(“Return From Use.”);

            await next.Invoke(context);

            });

            app.Run(async context => {

                        await context.Response.WriteAsync(“This is from Run.”);

            });

            }

 We are seeing that both strings from Use and Run have printed as output. Here, we should notice that we are forwarding the HTTP request to the next level by adding the following line.

 await next.Invoke(context);

 Otherwise, Use extension will not escalate HTTP requests and will behave as a Run Extension method.

app.Use(next=> async context =>

   {

            await context.Response.WriteAsync(“Return From Use.”);

   });

   Once we remove the next.Invoker(), we are getting output only from Use Extension.

Question  33. How to enable Session in ASP.NET Core?

Answer: The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to ASP.NET Core request pipeline.

public class Startup

 {

     public void ConfigureServices(IServiceCollection services)

     { 

         services.AddSession();

         services.AddMvc();

     }

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)

     {

        app.UseSession();

     }

 }

Question  34. What are the various JSON files available in ASP.NET Core?

Answer: There are following JSON files in ASP.NET Core :

  • Global.json: You can define the solution level settings in global.json file. If you will open the global.json file, you will see below code:

{

  “projects”: [ “src”, “test” ],

  “sdk”: {

            “version”: “1.0.0-preview2-003121”

  }

}

projects: projects property defines the location of source code for your solution. It specifies two locations for projects in the solution: src and test.src contains actual application and test contains any test.

  • Launchsettings.json:  In launchsettings.json file, You can define project specific settings associated with each profile Visual Studio is configured to launch the application, including any environment variables that should be used. You can define a framework for your project for compilation and debugging for specific profiles.

{

  “iisSettings”: {

            “windowsAuthentication”: false,

            “anonymousAuthentication”: true,

            “iisExpress”: {

            “applicationUrl”: “http://localhost:50944/&#8221;,

            “sslPort”: 0

            }

  },

  “profiles”: {

            “IIS Express”: {

            “commandName”: “IISExpress”,

            “launchBrowser”: true,

            “environmentVariables”: {

            “ASPNETCORE_ENVIRONMENT”: “Development”

            }

            },

            “ASPCoreMVCHelloWorld”: {

            “commandName”: “Project”,

            “launchBrowser”: true,

            “launchUrl”: “http://localhost:5000&#8221;,

            “environmentVariables”: {

            “ASPNETCORE_ENVIRONMENT”: “Development”

            },

            “kestrel”: {

            “commandName”: “kestrel”,

            “sdkVersion”: “dnx-clr-win-x86.1.0.0-preview2-003121”

            }

            }

  }

}

  • appsettings.json
  • bundleconfig.json
  • bower.json
  • package.json

Question  35. What is tag helper in ASP.NET Core?

Answer: It is a feature provided by Razor view engine that enables us to write server-side code to create and render the HTML element in view (Razor). The tag-helper is C# classes that used to generate the view by adding the HTML element. The functionality of tag helper is very similar to HTML helper of ASP.NET MVC.

Example:

 //HTML Helper

 @Html.TextBoxFor(model => model.FirstName, new { @class = “form-control”, placeholder = “Enter Your First Name” })

 //content with tag helper

 <input asp-for=”FirstName” placeholder=”Enter Your First Name” class=”form-control” />

 //Equivalent HTML

 <input placeholder=”Enter Your First Name” class=”form-control” id=”FirstName” name=”FirstName” value=”” type=”text”>

  Question  36. How to disable Tag Helper at element level?

  Answer: We can disable Tag Helper at element level using the opt-out character (“!”). This character must apply opening and closing the Html tag.

example:

 <!span asp-validation-for=”phone” class=”divPhone”></!span>

  Question  37. What are Razor Pages in ASP.NET Core?

  Answer: This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just like ASP.NET web forms. It supports all the features of ASP.NET Core.

example:

 @page

 <h1> Hello, Book Reader!</h1>

 <h2> This is Razor Pages </h2>

The Razor pages start with the @page directive. This directive handles requests directly without passing through the controller. The Razor pages may have code behind file, but it is not really code-behind file. It is a class inherited from the PageModel class.

Question  38. How can we do automatic model binding in Razor pages?

Answer: The Razor pages provide the option to bind property automatically when posting the data using BindProperty attribute. By default, it only binds the properties only with non-GET verbs. we need to set SupportsGet property to true to bind a property on getting request.

example:

 public class Test1Model : PageModel

 {

 [BindProperty]

 public string Name { get; set; }

 }

Question  39. How can we inject the service dependency into the controller?

Answer: There are three easy steps to add custom service as a dependency on the controller.

Step 1: Create the service

 public interface IHelloWorldService

 {

 string SaysHello();

 }

 public class HelloWorldService: IHelloWorldService

 {

 public string SaysHello()

 {

 return “Hello “;

 }

 }

Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)

 public void ConfigureServices(IServiceCollection services)

 {

 ….

 …

 services.AddTransient<IHelloWorldService, HelloWorldService>();

 …

 …

 }

Step 3: Use this service as a dependency in the controller

 public class HomeController: Controller

 {

 IHelloWorldService _helloWorldService;

 public HomeController(IHelloWorldService helloWorldService)

 {

 _helloWorldService = helloWorldService;

 }

 }

Question  40. How to specify service lifetime for register service that is added as a dependency?

Answer: ASP.NET Core allows us to specify the lifetime for registered services. The service instance gets disposed of automatically based on a specified lifetime. So, we do not care about cleaning these dependencies, it will be taken care of by ASP.NET Core framework. There are three types of lifetimes.

Singleton:

ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using the AddSingleton method of IServiceCollection. ASP.NET Core creates a service instance at the time of registration and subsequence requests use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.

Example:

            services.AddSingleton<IHelloWorldService, HelloWorldService>();

Transient:

ASP.NET Core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using the AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.

Example:

            services.AddTransient<IHelloWorldService, HelloWorldService>();

Scoped:

ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service is available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while service is registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like a singleton object.

Example:

services.AddScoped<IHelloWorldService, HelloWorldService>();

Question  41. What is the environment variable in the Dotnet core?

Answer: If you are using more than one connectionString then you can take advantage to set an environment variable. You can create multiple appsetting.json files like appsettings.dev.json, appsettings.qa.json, etc. Following code for retrieving your environment variable which you can set in launchSettings.json

//To retrieve your environment variable

            static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)

            {

            var env = ctx.HostingEnvironment;

            config.SetBasePath(env.ContentRootPath)

                        .AddEnvironmentVariables()

                        .AddInMemoryCollection()

                        .AddJsonFile($”appsettings.{env.EnvironmentName}.json”, optional: false, reloadOnChange: true);

            config.Build();

            }

Question  42. How to handle errors in middleware?

Answer: You can capture synchronous and asynchronous exception instances from the middleware pipeline and generate an HTML response. Following code has If the condition in which you can call different methods for development, staging, production environment or you can pass the environment name in the environment extension method.

Also, you can configure a custom error handling page to call the UseExceptionHandler method that adds a middleware to a pipeline that will catch the exception, log them, Re-executes the request in an alternate pipeline for the page or controller indicated. The request isn’t re-executed if the response has started.

if (env.IsDevelopment())

{

   app.UseDeveloperExceptionPage();

}

else

{

   app.UseExceptionHandler(“/Error”);

   app.UseHsts();

}

Question  43. Where static files are contained in asp.net core applications?

Answer: There is a folder called “wwwroot”, under this folder has several folders where you can find the CSS, js files.

  • Wwwroot
    • CSS
    • js
    • Lib

Question  44. Does real-time application support dot net core?

Answer: Yes, Asp.net’s core signalR is an open-source library that gives real-time web functionality to the application.

Question  45. What is the difference between app.Run and app.Use in asp.net core middleware pipeline?

Answer: Both are used to add a middleware delegate to the application request pipeline.

app.Run(): Insert a middleware without invoking the next middleware. It is just run.

app.Use(): Insert a middleware into the pipeline which invokes the next middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

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

            {

            await context.Response.WriteAsync(“Return from app.Use”);

            await next();

            });

            app.Run(async context => {

            await context.Response.WriteAsync(“Return from app.Run”);

            });

 //Below app.Use will not execute as app.Run does not execute next middleware

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

            {

            await context.Response.WriteAsync(“Return from app.Use”);

            await next();

            });

}

Question  46. What is the launchSettings.json file in asp.net core?

Answer: It holds the project-specific configuration to launch the application including the environment variable.

//launchSettings.json

{

  “iisSettings”: {

    “windowsAuthentication”: false,

    “anonymousAuthentication”: true,

    “iisExpress”: {

      “applicationUrl”: “http://localhost:63977&#8221;,

      “sslPort”: 44389

    }

  },

  “profiles”: {

    “IIS Express”: {

      “commandName”: “IISExpress”,

      “launchBrowser”: true,

      “environmentVariables”: {

        “ASPNETCORE_ENVIRONMENT”: “Development”

      }

    },

  “TestApp”: {

      “commandName”: “Project”,

      “launchBrowser”: true,

      “applicationUrl”: “https://localhost:5001;http://localhost:5000&#8221;,

      “environmentVariables”: {

        “ASPNETCORE_ENVIRONMENT”: “Development”

      }

    }

  }

}

Question  47. What are discontinued Technologies in .NET Core?

Answer:

  • Reflection: Has been converted into a lightweight version. An extension method called GetTypeInfo exposes information that you normally retrieve from a Type object. However, it is not as detailed as the original.
  • AppDomain: AppDomains isolate apps from each other. They require runtime support and are costly. Creating more app domains is unsupported and there aren’t any plans to add this in the future. Microsoft recommends using separate processes or containers as an alternative.
  • Remoting: .NET Remoting created several issues in its architectural design. Since it’s used for cross-AppDomain, which is no longer supported, it was decided to not support it either. It also cost them a lot due to runtime support.
  • Security Transparency: Due to security reasons, Security transparency is no longer supported. It used to separate sandbox code from security-critical code in a declarative method. Microsoft recommends you use security boundaries provided by the operating system itself. Such examples include virtualization, contained or user accounts.
  • Binary serialization

Question  48. What are the new features that brought Dotnet core 2.2?

Answer:

  • OpenAPI Analyzers & Convention
  • Problem details support
  • New Endpoint Routing
  • NET Core 2.2 adds support for HTTP/2
  • Options to configure Kestrel
  • NET Core 2.2 introduces a Java Client for SignalR
  • Performance of SocketsHttpHandler was improved by reducing connection pool locking contention.
  • Validation performance

Question  49. What is ASP.NET Core Module (ANCM)?

Answer: ASP.NET Core Module (ANCM) lets you run ASP.NET Core applications behind IIS and it works only with Kestrel; it isn’t compatible with WebListener. ANCM is a native IIS module that hooks into the IIS pipeline and redirects traffic to the backend ASP.NET Core application. ASP.NET Core applications run in a process separate from the IIS worker process, ANCM also does process management. ANCM starts the process for the ASP.NET Core application when the first request comes in and restarts it when it crashes. In short, it sits in IIS and routes the request for ASP.NET Core application to Kestrel.

Question  50. What is a Host and what’s the importance of Host in ASP.NET Core application?

Answer: ASP.NET Core apps require a host in which to execute. The host is responsible for application startup and lifetime management. Other responsibility of host’s includes ensuring the application’s services and the server are available and properly configured. Don’t confuse yourself with a Server. The host is responsible for starting the app and its management, where the server is responsible for accepting HTTP requests. The host is configured to use a particular server; the server is unaware of its host.

The host is typically created using an instance of a WebHostBuilder, which builds and returns a WebHost instance. The WebHost references the server that will handle requests.

In ASP.NET Core 1.1 looks like this:

public class Program

            {

            public static void Main(string[] args)

            {

            var host = new WebHostBuilder()

                        .UseKestrel()

                        .UseContentRoot(Directory.GetCurrentDirectory())

                        .UseIISIntegration()

                        .UseStartup<Startup>()

                        .Build();

            host.Run();

            }

            }

In ASP.NET Core 2.0, it is changed. It looks like this:

public class Program

{

            public static void Main(string[] args)

            {

            BuildWebHost(args).Run();

            }

            public static IWebHost BuildWebHost(string[] args) =>

            WebHost.CreateDefaultBuilder(args)

            .UseStartup<Startup>()

            .Build();

}

Question  51. What does WebHost.CreateDefaultBuilder() do?

Answer: This method does the following things.

  • Configure the app to use Kestrel as a web server.
  • Specify to use the current project directory as root directory for the application.
  • Setup the configuration sub-system to read setting from appsettings.json and appsettings.{env}.json to environment specific configuration.
  • Set Local user secrets storage only for the development environment.
  • Configure environment variables to allow for server-specific settings.
  • Configure command line arguments (if any).
  • Configure logging to read from the Logging section of the appsettings.json file and log to the Console and Debug window.
  • Configure integration with IIS
  • Configure the default service provider.

Question  52. What is the role of the IHostingEnvironmentinterface in ASP.NET Core?

Answer: ASP.NET Core offers an interface named IHostingEnvironment, allowing you to programmatically retrieve the current environment so you can have an environment-specific behaviour. By default, ASP.NET Core has 3 environments Development, Staging, and Production. Previously, the developers have to build the application differently for each environment (Staging, UAT, Production) due to dependency on config file sections and the preprocessor directive applicable at compile time. ASP.NET Core takes a different approach and uses IHostingEnvironment to retrieve the current environment. You can also define a custom environment like QA or UAT.

Question  53. What is the use of UseIISIntegration?

Answer: This tells ASP.NET that IIS will be working as a reverse proxy in front of Kestrel. As if you expose your application to the Internet, you must use IIS, Nginx, or Apache as a reverse proxy server. When you wish to deploy your ASP.NET Core application on windows, you need to tell ASP.NET Core Host to use IIS integration.

UseKestrel and UseIISIntegration must be used in conjunction as UseKestrel creates the web server and hosts the code. UseIISIntegration specifies IIS as the reverse proxy

var host = new WebHostBuilder()

            .UseKestrel()

            .UseContentRoot(Directory.GetCurrentDirectory())

            .UseIISIntegration()

            .UseStartup<Startup>()

            .Build();

Question  54. What are the different ways for bundling and minification in ASP.NET Core?

Answer: There are different ways for bundling and minification in ASP.NET Core.

  • Gulp: was the default choice for ASP.NET Core till beta versions. Later it was removed due to performance and speed issues and replaced with BundlerMinifier. Read this post to find out the reasons for this decision.
  • BundlerMinifier: is a Visual Studio extension and it’s default choice now. You should see the bundleconfig.json file in your default template. Read this post to know more about bundling and minification in ASP.NET Core.
  • ASP.NET Core Web Optimizer: ASP.NET Core middleware for bundling and minification of CSS and JavaScript files at runtime.
  • Grunt: can also be used with ASP.NET Core.

Question  55. What’s the difference between .NET Core .NET Framework and .NET Standard?

Answer:

  • .NET Standard is a specification for implementing the Base Class Library (BCL). BCL contains classes such as exception handling, XML, collections, I/O and networking. WPF, WCF and ASP.NET do not form part of BCL and so are not included in .NET Standard library.
  • .NET Core is a managed framework that builds desktop and web applications in cross-platform.
  • .NET Framework is a framework that builds desktop and web applications in Windows only. It is highly dependent on the architecture.
  • Both “.NET Core” and “.NET Framework” include .NET Standard for BCL in their managed framework.

Question  56. What is the IWebHostEnvironment interface used for?

Answer: IWebHostEnvironment is an interface for .NET Core. It is used to get information on the web hosting environment an application is executing in. It needs to be injected as a dependency on the controller. The interface has two properties:

  • WebRootPath – Path of the WWW folder
  • ContentRootPath – Path of the root folder which includes all the application files.

Question  57. What is the difference between UseIIS & UseIISIntegration?

Answer: Before ASP.NET Core 2.2, ASP.NET Core was hosted outside of the IIS process. This meant that we had two processes for ASP.NET core application:

  • w3wp.exe – the IIS Process
  • dotnet.exe – the ASP.NET Core process. This is where the Kestrel web server was started.

IIS and Kestrel communicated between these two mentioned processes. In this case, you need to use UseIISIntegration.

However, in later versions, ASP.NET Core introduced in-process hosting. ASP.NET Core no longer runs separately but runs inside the IIS w3wp.exe process. This removes the need for the Kestrel web server. For this case, you would need to specify UseIIS.

Question  58. What is Dependency Injection and how is it implemented in ASP.NET Core?

Answer: A dependency is any object that is required from another object. Here is an example of a dependency:

public class DependencyClass

{

            public DependencyClass(){ }

            public Task SayHello(string name)

            {

            Console.WriteLine(

            $”Hello to you, {name}”);

            return Task.FromResult(0);

            }

}

Now, an instance can be created from DependencyClass to get access to the ‘SayHello’ method. DependencyClass now becomes a dependency of the AboutModel. See example below:

public class AboutModel : PageModel

{

            DependencyClass _dependencyClass = new DependencyClass();

            public async Task IntroduceAsync()

            {

            await _dependencyClass.SayHello(

            “AboutModel.IntroduceAsync created this message”);

            }

}

This creates a problem because code dependencies (as above example) are problematic and it is recommended not to use where possible. Reasons for this are the following:

In order to replace DependencyClass with a different implementation, the class itself must be modified.

If DependencyClass has dependencies, they must be set up by the class. With large projects containing multiple classes depending on DependencyClass, this will be cumbersome.

It will be hard to unit test. DependencyClass cannot be mocked or stubbed in this case.

This is where Dependency injection comes in. This is how it addresses these problems in ASP.NET Core:

Interface or base class as an abstraction for the dependency implementation (IDependencyClass)

The dependency must be registered as a service inside a service container. ASP.NET Core contains a built-in service container, IServiceProvider. Services are registered in the app’s Startup configure method.

The service is then injected into the constructor in the class it’s used in. The framework takes care of instantiating the dependent and disposing of it.

The above technique is called Inversion of Control (IoC) between classes and their dependencies.

Question  59. What is a Request delegate?

Answer: Request delegates handle each HTTP request and are used to build the request pipeline. It can be configured using Run, Map and Use extension methods. An request delegate can be in-line as an anonymous method (called in-line middleware) or a reusable class. These classes or in-line methods are called middleware components.

Question  60. How to read values from Appsettings.json file?

Answer: You can read values from appsettings.json using below code

class Test

{

// requires using Microsoft.Extensions.Configuration;

 private readonly IConfiguration Configuration;

            public TestModel(IConfiguration configuration)

            {

            Configuration = configuration;

            }

// public void ReadValues(){

var val = Configuration[“key”]; // reading direct key values

var name = Configuration[“Employee:Name”]; // read complex values

}

}

Default configuration provider first loads the values from appsettings.json and then from appsettings.Environment.json file.

Environment specific values override the values from appsettings.json file. In the development environment appsettings.Development.json file values override the appsettings.json file values, same apply to production environment.

Question  61. How does ASP.NET Core serve static files?

Answer: In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are served directly to the clients. ASP.NET Core template provides a root folder called wwwroot which contains all these static files. UseStaticFiles() method inside Startup.Configure enables the static files to be served to clients.

You can serve files outside of this webroot folder by configuring Static File Middleware as follows.

app.UseStaticFiles(new StaticFileOptions

            {

            FileProvider = new PhysicalFileProvider(

            Path.Combine(env.ContentRootPath, “MyStaticFiles”)), // MyStaticFiles is new folder

            RequestPath = “/StaticFiles”  // this is requested path by client

            });

// now you can use your file as below

<img src=”/StaticFiles/images/profile.jpg” class=”img” alt=”A red rose” />

 // profile.jpg is image inside MyStaticFiles/images folder

Question  62. Explain Session and State management in ASP.NET Core

Answer: As we know HTTP is a stateless protocol. HTTP requests are independent and do not retain user values. There are different ways to maintain user state between multiple HTTP requests.

  • Cookies
  • Session State
  • TempData
  • Query strings
  • Hidden fields
  • HttpContext.Items
  • Cache

Question  63. Explain the Caching or Response caching in ASP.NET Core.

Answer: Caching significantly improves the performance of an application by reducing the number of calls to actual data sources. It also improves the scalability. Response caching is best suited for data that changes infrequently. Caching makes the copy of data and stores it instead of generating data from the original source.

Response caching headers control the response caching. ResponseCache attribute sets these caching headers with additional properties.

Question  64. What is In-memory cache?

Answer: In-memory cache is the simplest way of caching by ASP.NET Core that stores the data in memory on a web server.

Apps running on multiple servers should ensure that sessions are sticky if they are using in-memory cache. Sticky Sessions responsible to redirect subsequent client requests to the same server. In-memory cache can store any object but distributed cache only stores byte[].

The IMemoryCache interface instance in the constructor enables the In-memory caching service via ASP.NET Core dependency Injection.

Question  65. What is Distributed caching?

Answer: Applications running on multiple servers (Web Farm) should ensure that sessions are sticky. For Non-sticky sessions, cache consistency problems can occur. Distributed caching is implemented to avoid cache consistency issues. It offloads the memory to an external process. Distributed caching has certain advantages as below.

  • Data is consistent across client requests to multiple server
  • Data keeps alive during server restarts and deployments.
  • Data does not use local memory

IDistributedCache interface instances from any constructor enable distributed caching service via Dependency Injection.

Question  66. What is XSRF or CSRF? How to prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core?

Answer: Cross-Site Request Forgery (XSRF/CSRF) is an attack where an attacker that acts as a trusted source sends some data to a website and performs some action. An attacker is considered a trusted source because it uses the authenticated cookie information stored in the browser.

For example a user visits some site ‘www.abc.com’ then browser performs authentication successfully and stores the user information in cookie and perform some actions, In between user visits some other malicious site ‘www.bad-user.com’ and this site contains some code to make a request to vulnerable site (www.abc.com). It’s called cross site part of CSRF.

How to prevent CSRF?

  • In ASP.NET Core 2.0 or later FormTaghelper automatically injects the antiforgery tokens into the HTML form element.
  • You can add manually antiforgery tokens in HTML forms by using @Html.AntiForgeryToken() and then you can validate it in the controller by ValidateAntiForgeryToken() method.

Question  67. What is a PreFlight request?

Answer: A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.

It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.

A preflight request is automatically issued by a browser and in normal cases, front-end developers don’t need to craft such requests themselves. It appears when a request is qualified as “to be preflighted” and omitted for simple requests.

A preflight request is automatically issued by a browser and in normal cases, front-end developers don’t need to craft such requests themselves. It appears when a request is qualified as “to be preflighted” and omitted for simple requests.

For example, a client might be asking a server if it would allow a DELETE request, before sending a DELETE request, by using a preflight request:

OPTIONS /resource/foo

Access-Control-Request-Method: DELETE

Access-Control-Request-Headers: origin, x-requested-with

Origin: https://foo.bar.org

If the server allows it, then it will respond to the preflight request with an Access-Control-Allow-Methods response header, which lists DELETE:

HTTP/1.1 204 No Content

Connection: keep-alive

Access-Control-Allow-Origin: https://foo.bar.org

Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE

Access-Control-Max-Age: 86400

The preflight response can be optionally cached for the requests created in the same url using Access-Control-Max-Age header like in the above example.

Question  68. What is routing in ASP.NET Core?

Answer: Routing is functionality that maps incoming requests to the route handler. The route can have values (extract them from URL) that are used to process the request. Using the route, routing can find route handlers based on URL. All the routes are registered when the application is started. There are two types of routing supported by ASP.NET Core

  • The conventional routing
  • Attribute routing

The Routing uses routes for map incoming requests with route handler and Generate URL that is used in response. Mostly, the application having a single collection of routes and this collection are used for the process of the request. The RouteAsync method is used to map incoming requests (that match the URL) with available route collection.