Asp.Net Core Interview Questions

Q. What is Metapackages?
Ans.

The framework .NET Core 2.0 introduced Metapackage that includes all the supported package 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 provide by ASP.NET core.
Q. What are the benefits of using ASP.NET Core over ASP.NET?
Ans.


Q. What are the various JSON files in ASP.NET Core?
Ans.

Global.json
appsetting.json
Project.json
launchsetting.json
libman.json
package.json

Q. What is Kestral?
Ans.

Q. What is the difference between IIS and Kestrel? Why do we need two web servers?
Ans.

  • The main difference between IIS and Kestrel is that Kestrel is a cross-platform server. It runs on Windows, Linux, and Mac, whereas IIS only runs on Windows.
  • Another essential difference between the two is that Kestrel is fully open-source, whereas IIS is closed-source and developed and maintained only by Microsoft.
  • IIS is very old software and comes with a considerable legacy and bloat. With Kestrel, Microsoft started with high-performance in mind. They developed it from scratch, which allowed them to ignore the legacy/compatibility issues and focus on speed and efficiency.
  • However, Kestrel doesn’t provide all the rich functionality of a full-fledged web server such as IIS, Nginx, or Apache. Hence, we typically use it as an application server, with one of the above servers acting as a reverse proxy.

Q. What is Middleware?
Ans.

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:
  • Chooses whether to pass the request to the next component in the pipeline.
  • Can perform work before and after the next component in the pipeline.

In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware from processing the request.
Typically, there will be multiple middleware in ASP.NET Core web application. It can be either framework provided middleware, added via NuGet or your own custom middleware. We can set the order of middleware execution in the request pipeline. Each middleware adds or modifies http request and optionally passes control to the next middleware component. The following figure illustrates the execution of middleware components.
Q. What is the difference between app.Use() , app.Map(),app.Run()?
Ans.

app.use() and app.Run()We can use both the methods in Configure methods of startup class. Both are used to add middleware delegate to the application request pipeline.
app.Use()
To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it includes next parameter to invoke next middleware in the sequence.
Ex:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Hello World From 1st Middleware!");
        await next();
    });
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World From 2nd Middleware");
    });
}
                                
app.Run()
The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate. The RequestDelegate is a delegate method which handles the request.
Run Method Signature:
public static void Run(this IApplicationBuilder app, RequestDelegate handler)
Request Delegate Signature:
public delegate Task RequestDelegate(HttpContext context);
The Run method accepts a method as a parameter whose signature should match with RequestDelegate.
Therefore, the method should accept the HttpContext parameter and return Task. So, you can either specify a lambda expression or specify a function in the Run method.
The Run method adds a terminal middleware so it cannot call next middleware as it would be the last middleware in a sequence.
Ex:
public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Run(MyMiddleware);
    }
    private Task MyMiddleware(HttpContext context)
    {
        return context.Response.WriteAsync("Hello World! ");
    }
}
(or)
app.Run(async context => await context.Response.WriteAsync("Hello World!") );
(or)
app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

app.Map() :
It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path matching. If request path starts with the given path, middleware on to that branch will execute.
Ex : 
public void Configure(IApplicationBuilder app)
{
    app.Map("/path1", Middleware1);
    app.Map("/path2", Middleware2);
}

Q. What is the use of launchSettings.json?
Ans.
This json file holds project specific settings associated with each debug profile, Visual Studio is configured to use to launch the application, including any environment variables that should be used. You can define framework for your project for compilation and debugging for specific profiles.
Q. Can we change wwwroot file name?
Ans.
You can rename wwwroot folder to any other name as per your choice and set it as a web root while preparing hosting environment in the program.cs.
let's rename wwwroot folder to Content folder. Now, call UseWebRoot() method to configure Content folder as a web root folder in the Main() method of Program class as shown below.
Ex:
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory())
         .UseWebRoot("Content")
         .UseIISIntegration()
         .UseStartup()
         .Build();

        host.Run();
     }
}

Q. What is the use of wwwroot?
Ans.
ASP.NET Core project is treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root.
Only those files that are in the web root - wwwroot folder can be served over an http request. All other files are blocked and cannot be served by default.
We will maintain separate folders for the different types of static files such as JavaScript, CSS, Images, library scripts etc.
You can access static files with base URL and file name. For example, we can access above app.css file in the css folder by http://localhost:/css/app.css.
you need to include a middleware for serving static files in the Configure method of Startup.cs.
app.UseStaticFiles() method adds StaticFiles middleware into the request pipeline. The UseStaticFiles is an extension method included in the StaticFiles middleware so that we can easily configure it.
Q. What is the difference between UseDefaultFiles() and UseFileServer()
Ans.

The UseDefaultFiles configures the DefaultFiles middleware which is a part of StaticFiles middleware. This will automatically serve html file named default.html, default.htm, index.html or index.htm on the http request http://localhost:
To serve default.html on the root request http://localhost: , call UseDefaultFiles() method before UseStaticFiles() in the Configure method
Ex : 
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseDefaultFiles(); app.UseStaticFiles(); | | }

Note: Order of middleware is very important. app.UseDefaultFiles() should be added before app.UseStaticFiles() in the request pipeline.

The FileServer middleware combines the functionalities of UseDefaultFiles and UseStaticFiles middlware. So, instead of using both the middlware, just use UseFileServer in the Configure method.
Ex : 
UseFileServer = UseDefaultFiles + UseStaticFiles

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseFileServer();
        |
        |
}
Q. What is the use of UseDeveloperExceptionPage
Ans.
The UseDeveloperExceptionPage extension method adds middleware into the request pipeline which displays developer friendly exception detail page. This helps developers in tracing errors that occur during development phase.
As this middleware displays sensitive information, it is advisable to add it only in development environment.
Ex:
public class Startup
{
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         if (env.IsDevelopment() || env.IsStaging())
         {
            app.UseDeveloperExceptionPage();
         }
         app.Run(context => { throw new Exception("error"); });
    }
}

the developer exception page includes 4 tabs: Stack, Query, Cookies, and Headers. Stack tab displays information of stack trace, which indicates where exactly an error occurred. Query tab displays information about query string. Cookies tab displays information about cookies set by the request and Headers tab displays information about headers.
Q. What is the use of UseExceptionHandler?
Ans.
In MVC Core application, we might want some other controller to handle all exceptions and display custom user friendly error messages. The UseExceptionHandler extension method allows us to configure custom error handling route. This is useful when an application runs under production environment.
Ex : 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment() || env.IsStaging())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/Home/Error");
     }
     //code removed for clarity
}
Q. How to Access Environment Variable at Runtime?
Ans.
The IHostingEnvironment service includes EnvironmentName property which contains the value of ASPNETCORE_ENVIRONMENT variable. ASP.NET Core also includes extension methods to check the environment such as IsDevelopment(), IsStating(), IsEnvironment() and IsProduction().
The IHostingEnvironment service is provided by ASP.NET hosting layer and can be used anywhere in your application via Dependency Injection.
Ex : 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsEnvironment("Development"))
    {
         // code to be executed in development environment
    }
    if (env.IsDevelopment())
    {
         // code to be executed in development environment
    }
    if (env.IsStaging())
    {
        // code to be executed in staging environment
    }
    if (env.IsProduction())
    {
        // code to be executed in production environment
    }
}

Q. What is the use of Startup.cs?
Ans.
  • ASP.NET Core application must include Startup class. It is like Global.asax in the traditional .NET application. As the name suggests, it is executed first when the application starts.
  • The startup class can be configured using UseStartup() method at the time of configuring the host in the Main() method of Program class
  • The name "Startup" is by ASP.NET Core convention. However, we can give any name to the Startup class, just specify it as the generic parameter in the UseStartup() method. For example, to name the Startup class as MyStartup, specify it as .UseStartup().
  • Startup class includes two public methods: ConfigureServices and Configure.

Q. What is the use of ConfigureService method in Startup?
Ans.
  • The Dependency Injection pattern is used heavely in ASP.NET Core architecture. It includes built-in IoC container to provide dependent objects using constructors.
  • The ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container.
  • After registering dependent class, it can be used anywhere in the application. You just need to include it in the parameter of the constructor of a class where you want to use it. The IoC container will inject it automatically.
  • ASP.NET Core refers dependent class as a Service. So, whenever you read "Service" then understand it as a class which is going to be used in some other class.
  • ConfigureServices method includes IServiceCollection parameter to register services to the IoC container.

Q. What is the use of Configure method in Startup?
Ans.
  • The Configure method is a place where you can configure application request pipeline for your application using IApplicationBuilder instance that is provided by the built-in IoC container.
  • ASP.NET Core introduced the middleware components to define a request pipeline, which will be executed on every request.
  • We include only those middleware components which are required by your application and thus increase the performance of your application.
  • The Configure method includes three parameters IApplicationBuilder, IHostingEnvironment, and ILoggerFactory by default. These services are framework services injected by built-in IoC container.
  • At run time, the ConfigureServices method is called before the Configure method. This is so that you can register your custom service with the IoC container which you may use in the Configure method.