Tech Point Fundamentals

Sunday, October 9, 2022

.Net Core Interview Questions and Answers - Part 06

ASP.Net Core Interview Questions and Answers - Part 06

AspDotNetCoreInterviewQuestionsAndAnswers

Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 6th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:






ASP.Net Core Interview Questions and Answers - Part 06


Q053. What is WebListener? When you should use WebListner?

We know that ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers.

WebListener is a Windows-only HTTP server for ASP.NET Core.  It runs directly on the Http.Sys kernel driver, and has very little overhead. 

WebListener is a web server for ASP.NET Core that runs only on Windows host machines, based on the Windows HTTP Server API. WebListener can be used for direct connection to the Internet without relying on IIS. It can only be used independently.

It is an alternative to Kestrel and is built on HttpSys kernel-mode driver. Also, is used for direct connection to the internet without the need of an IIS as a reverse proxy server. But it is not compatible with IIS.



When and Why to Use WebListner:

If you are on Windows and you want to expose your server directly to the internet you can use WebListner. Because Kestrel is not certified for direct exposure.

You can use WeListner if you need any of the below features:
  1. Windows Authentication
  2. Port sharing
  3. HTTPS with SNI
  4. HTTP/2 over TLS (Windows 10)
  5. Direct file transmission
  6. Response caching



How to Download and Configure WebListner:

Web Listener is now available on NuGet. You can download and install it from nugget:

InstallWebListner

You can add support for WebListener to your ASP.NET application by adding the “Microsoft.AspNetCore.Server.WebListener” dependency in project.json and the following command:

"web": "Microsoft.AspNetCore.Hosting --server Microsoft.AspNetCore.Server.WebListener --server.urls http://localhost:5000"

Now you can use the WebListner in the main method():

public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseWebListener(options =>
{
options.ListenerSettings.Authentication.Schemes =             AuthenticationSchemes.NTLM;
options.ListenerSettings.Authentication.AllowAnonymous = false;
})
.UseStartup()
.Build();

host.Run();
}




Q054. What is a Self-Hosting or Self-hosted Web Application?

Self Hosting means the application itself uses the built-in Web Server, which is in contrast to classic ASP.NET Framework Web Apps which typically require IIS or the built-in WebDev server to run. But a Self-hosting web application can't restart automatically on system boot and restart or in the event of a failure.

ASP.NET Core is fully decoupled from the webserver environment hosting the application. It is possible to self-host an ASP.NET Core Application without IIS. In fact, all ASP.NET Core applications are self-hosted. Even in production, IIS/Nginx/Apache is a reverse proxy for the self-hosted application.

All the .NET Core Apps are self-hosting Console Apps where they use their own HTTP Server, instead of needing to rely on an external HTTP Server. However, for prod deployment, they’re typically hosted behind a full-featured reverse proxy server like IIS, Apache, or Nginx to access its more robust features like multiple Virtual Hosts behind a single domain, configuring SSL Certs, etc.

The .Net Core apps still support IIS and IIS Express but by default, it uses self-hosting scenarios by using Kestrel and WebListener HTTP Servers.  The IISIntegration() is optional which is only necessary if you want to integrate with IIS.  ASP.NET 5 supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers. 



Q055. What is Host in ASP.NET Core? What is the difference between Host and WebHost?

A Host encapsulates all the resources for the app. ASP.NET Core apps configure and launch a host. On startup, the ASP.NET Core application creates the host. 

A host is an object that encapsulates an app's resources. The resources which are encapsulated by the host include HTTP Server implementation, Dependency Injection, Configuration, Logging, Middleware, etc.

The host is responsible for app startup and lifetime management. At a minimum, the host configures a server and a request processing pipeline. The host can also set up logging, dependency injection, and configuration.

The ASP.NET Core templates create a WebApplicationBuilder and WebApplication, which is recommended for web apps. The host is typically configured, built, and run by code in the Program.cs.  A host is created using an instance of IWebHostBuilder. This is typically performed in the app's entry point, the Main method in Program.cs.



public class Program 
public static void Main(string[] args) 
var config = new ConfigurationBuilder()
  .AddCommandLine(args)
  .AddEnvironmentVariables(prefix: "ASPNETCORE_").Build(); 

var host = new WebHostBuilder()
  .UseConfiguration(config)
  .UseKestrel()
  .UseContentRoot(Directory.GetCurrentDirectory())
  .UseStartup<Startup>().Build(); 
host.Run(); 
}

When a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService registered in the service container's collection of hosted services. In a web app, one of the IHostedService implementations is a web service that starts an HTTP server implementation.

Host vs WebHost:

There is a parallel set of classes Host/WebHost and HostBuilder/WebHostBuilder. The purpose of these classes is the same – to allow a single object to control the application’s startup and graceful shutdown. WebHost is from previous versions of the .NET Core and it still exists as of today in .NET 5, because of backward compatibility reasons.




Q056. What is a Generic Host in .NET Core? 

The ASP.NET Core templates create a WebApplicationBuilder and WebApplication, which provide a streamlined way to configure and run web applications without a Startup class

 There are two hosts in .Net Core:

  1. .NET Generic Host
  2. ASP.NET Core Web Host

The Worker Service templates create a .NET Generic Host, HostBuilder. The Generic Host can be used with other types of .NET applications, such as Console apps. .NET Generic Host is recommended and ASP.NET Core template builds a .NET Generic Host on app startup. ASP.NET Core Web host is only used for backward compatibility.



As of ASP.NET Core 3, they exported ASP.NET code to run on a .NET Generic Host instead of the previously used WebHost. .NET Generic Host is a non-web version of the WebHost that runs on ASP.NET Core. It is an abstraction layer for both Web and non-web functionality.

Generic Host decoupled the HTTP pipeline from the Web Host API to enable a wider collection of host environments. The generic host was previously present as ‘Web Host’, in .NET Core for web applications. Later, the ‘Web Host’ was deprecated and a generic host was introduced to cater to the web, Windows, Linux, and console applications. 

The generic host was previously present as ‘Web Host’ in .NET Core for web applications. Later, the ‘Web Host’ was deprecated and a generic host was introduced to cater to the web, Windows, Linux, and console applications. 




Q057. What is IWebHost interface in ASP.NET Core?

The IWebHost is the core of your ASP.NET Core application, containing the application configuration and the Kestrel server that listens for requests and sends responses.

IWebHost is one of the building blocks of ASP.NETCore which contains the application configuration and kestrel server. The IWebHost represents a configured web host. It has Start(), StartAsync(CancellationToken), and StopAsync(CancellationToken), Run(IWebHost), WaitForShutdown(IWebHost) methods.

The Program.cs is the place where you build an IWebHost instance, using a WebHostBuilder. The helper method, WebHost.CreateDefaultBuilder() can be used to create a WebHostBuilder that uses the Kestrel HTTP server, loads configuration settings, sets up logging, and adds IIS integration if necessary. Calling Build() creates the IWebHost instance.



public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args)
.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}


You can start the web server and begin accepting HTTP requests by calling Run on the IWebHost.



Q058. What is WebHostBuilder() method in .Net Core? What is the difference between HostBuilder vs WebHostBuilder?

WebHostBuilder is a builder for IWebHost. It is defined in Microsoft.AspNetCore.Hosting namespace. The Generic Host Builder in ASP .NET Core was introduced in v2.1, but only meant for non-HTTP workloads. However, it has now replaced the Web Host Builder as of v3.0 in 2019.

HostBuilder is a static class that provides two methods and when we call these methods, they will add some features into ASP.NET Core Applications. One method is without a parameter and the other method takes a string array as an argument.

The purpose of the Build method is to build the required services and a Microsoft.AspNetCore.Hosting.IWebHost which hosts a web application. It is used to build up the HTTP pipeline via webHostBuilder.Use() chaining it all together with WebHostBuilder.Build() by using the builder pattern.



Q059. What is the use of IWebHostEnvironment? What is the difference between IWebHostEnvironment and IHostingEnvironment in .Net Core? Why Server.MapPath() not working in ASP.Net Core?

The Server.MapPath() is not working in ASP.Net Core because Microsoft has permanently removed Server.MapPath() function from .Net Core.

Microsoft has introduced a new interface IHostingEnvironment for .Net Core 2.0 and IWebHostEnvironment for .Net Core 3.0 onwards.  IWebHostEnvironment has replaced IHostingEnvironment in .Net Core 3.0  onwards.

IWebHostEnvironment Provides information about the web hosting environment an application is running in. It belongs to the namespace Microsoft.AspNetCore.Hosting namespace.

Both of these interfaces (IWebHostEnvironment or IHostingEnvironment) need to be injected as a dependency in the Controller and then later used throughout the Controller. It is used to get information on the web hosting environment an application is executing in.



The IWebHostEnvironment interface has two properties:

  1. WebRootPath which specifies the path for www folder.
  2. ContentRootPath which specifies the root folder which contains all the Application files.

public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController( IWebHostEnvironment _environment)
{           
Environment = _environment;
}
public IActionResult Index()
{
string wwwPath = this.Environment.WebRootPath;
string contentPath = this.Environment.ContentRootPath;
return View();
}
}




Q060. What is HttpContext? How to access HttpContext in ASP.NET Core?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

HttpContext object created by ASP.NET Core web server. It contains information about request-specific services, configuration details, data loads, and error information and it is passed to the entire application.

You can access and use it from Razor Page View, Controller, middleware, SignalR, and custom components as well.

var pathBase = HttpContext.Request.PathBase;



Q061. What is the Application Startup Process in Asp.net Core? What is the use of startup.cs file in ASP.Net Core?

We know that in ASP.NET, Global.asax acts as the entry point for your application. But in ASP.Net Core the startup.cs is the entry point for your application.

The startup.cs file is the entry point of the application that must be included in the asp.net core application. ASP.Net Core project includes Startup.cs file which gets executed as soon as applications get started.

This class handles two important aspects of your application, namely service registration, and middleware pipeline. It contains two important methods:

  1. ConfigureServices() method for configuring the application service. It is used to add services to the container.
  2. Configure()  method which is for configuring the HTTP request pipeline.

The Startup.cs class is called from the program.cs file. 



Use of Startup.cs Class: The startup class is used to define application components and features. This class required changes frequently. The startup class is responsible for configuration-related things like:

  1. Configuring the services required by the application at a central place
  2. Defining the application's request handling pipeline as a series of middleware components.
The middleware pipeline is the sequence in which your application processes an HTTP request.



public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
services.AddRazorPages();  
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}




Q062. What is the use of Program.cs class in MVC.Net core?

Everything starts from Program.cs file. The Program.cs class is the entry point of our application.  An ASP.NET application starts in the same way as a console application, from a static void Main() function.

This class configures the web host that will serve the requests. The host is responsible for application startup and lifetime management, including graceful shutdown.

At a minimum, the host configures a server and a request processing pipeline. The host can also set up logging, configuration, and dependency injection.

The Startup.cs is called from the program.cs file. Program class is used to define required infrastructure to an application like Application settings, Logging, Web Server related, etc. This class required changes rarely.



public class Program
{
public static void Main(string[] args)
{
   CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseKestrel()
.UseStartup<Startup>();
}

To Be Continued Part-07...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

    

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.