Tech Point Fundamentals

Sunday, October 16, 2022

.Net Core Interview Questions and Answers - Part 07

ASP.Net Core Interview Questions and Answers - Part 07

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 7th 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 to the current part:






ASP.Net Core Interview Questions and Answers - Part 07


Q063. What is ConfigureServices() method in .NET Core? Is it mandatory to define the ConfigureServices method? Where does the ConfigureServices() method defined in the .Net Core application? 

The startup.cs class includes two public methods: ConfigureServices and ConfigureSo both ConfigureServices() and Configure() methods are defined within startup.cs file.

The ConfigureServices() method is defined in the startup.cs file. It is used to define and register the services used by the application like ASP.NET MVC Core framework, Entity Framework Core, CORS, Logging, MemoryCaching, etc.

A ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container. After registering the 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 that is going to be used in some other class. ConfigureServices method includes the IServiceCollection parameter to register services to the IoC container. 

Even though we will almost always use this method, it is an optional method. If ConfigureServices exists on the Startup class, it will be called by the Web host. To do so, the Web host has to instantiate the Startup first. Therefore, the Startup constructor will execute before ConfigureServices.

By default, ConfigureServices() has one parameter, of type IServiceCollection. The IServiceCollection interface is a container. Adding services to this container will make them available for dependency injection.  That means we can inject those services anywhere in our application.



public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IEmailSender, EmailSender>();
   services.AddTransient<IService1, Service1>();
    services.AddScoped<IService2, Service2>();
}

The ConfigureServices() method gets called at runtime to register services to the DI container. After registering for the dependent classes, you can use those classes anywhere in the application. The ConfigureServices method includes the IServiceCollection parameter to register services to the DI container.



Q064. What is Configure() method in .NET Core? Where does the Configure() method defined in the .Net Core application?

ASP.NET Core introduced the middleware components to define a request pipeline, which will be executed on every request. You include only those middleware components which are required by your application and thus increase the performance of your application. It is usually defined in the startup.cs file.

The Configure() method is a place where you can configure the application request pipeline for your application using the IApplicationBuilder instance that is provided by the built-in IoC container. In Configure() method, we set up middleware that handles every HTTP request that comes to our application.

ConfigureServices() method takes care of registering services which are consumed across the application using Dependency Injection or Application Services. This method gets called by the runtime.  So Configure() method is used to define the middleware in the HTTP request pipeline. All the components that are assembled into an application pipeline to handle requests and responses are the middleware. 

By default, the Configure() method includes three parameters IApplicationBuilder, IHostingEnvironment, and ILoggerFactory by default. These services are framework services injected by a built-in IoC container.



public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory log)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}  
app.UseBrowserLink();  
app.UseMvc();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}

But Remember Ordering matters in Configure method, so the first piece of code inside of the method will process the request first. It can either make a response or pass the request to the next piece of middleware.

At run time, the ConfigureServices() method is called before the Configure() method. This is so because you can register your custom services with the IoC container which you may use within the Configure() method.

You can configure the services and middleware components without the Startup class and its methods, by defining this configuration inside the Program class in the CreateHostBuilder method directly as well.



Q065. What is the difference between the ConfigureServices() and Configure() methods of the Startup.cs class? 

ASP.NET Core application must include the Startup class The startup class is executed very first when the application starts. It is like Global.asax in the traditional .NET application. The startup class can be configured using UseStartup<T>() method at the time of configuring the host in the Main() method of the Program class.

The startup.cs class includes two public methods: ConfigureServices and Configure. So both ConfigureServices() and Configure() methods are defined within startup.cs file.

The Startup class must include a Configure() method and can optionally include ConfigureService() method. So the ConfigureService() is optional while Configure() method is mandatory.

ConfigureServices() method is used to register the service with IServiceCollection to the IoC container while Configure method is used to configure the middleware pipeline for handling HTTP requests.

At run time, the ConfigureServices() method is called before the Configure() method by the host. This is so because you can register your custom services with the IoC container in ConfigureServices() method which you may use within the Configure() method.



You can configure the services and middleware components without the Startup class and its methods, by defining this configuration inside the Program class in the CreateHostBuilder method directly as well.

public class Startup
{
Public void ConfigureServices(IServiceCollection service)
{
services.AddEntityFramework();
}
Public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}

After that this startup file is used by the main() method of the Program class:

public class Program
{
public static void Main(string[] args)
{
host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.run();
}
}



Q066. What is the use of the .csproj file in .Net Core? How it is different from the traditional ASP.Net's .csproj file?

ASP.NET Core 1.0 does not create a .csproj file, instead, it uses .xproj and project.json files to manage the project. This has changed in ASP.NET Core 2.0. Visual Studio now uses the .csproj file to manage projects.

If you are using C# as the programming language then it will create the project file with the “.csproj” extension. Similarly, in traditional ASP.Net if you are using VB as the programming language, then it will create the project file with the “.vbproj” extension. 

The .csproj is one of the most important files in an ASP.NET project. It is like a package.json file of a Node.js application. The .csproj file includes settings related to targeted .NET Core Framework, project folders, NuGet package references, etc. The .csproj file tells dotnet how to build the ASP.NET application.



ASP.Net Core vs Class ASP.Net Project File:

1. The ASP.NET Core Project files and folders are synchronized with physical files and folders. If you add a new file in the project folder then it will directly reflect in the solution explorer immediately. You don’t need to add it to the project explicitly by right-clicking on the project like we were doing in the traditional ASP.Net projects.

2. In the previous traditional versions of ASP.NET Framework, when we add a folder or a file to the project using Solution Explorer, then a reference to that folder or file is added in the project file. But with ASP.NET Core, the Project File does not include any reference for the Files or Folders added to the project using Solution Explorer. 

3. In ASP.NET Core the File System determines what folders and files belong to the project automatically. Usually, all the files and folders which are present at the project root folder are part of the project and only they are only going to display in the Solution Explorer.



So, when you add or delete any file or a folder using File Explorer also, then that file or folder becomes part of the project. So as soon as you add a file or folder using the file explorer, it is immediately displayed in the solution explorer.

4. In the previous versions of ASP.NET Framework, in order to edit the project file: first we need to unload the project, then edit the project file, save the project file and then finally reload the project.

But with ASP.NET Core we can edit the project file without unloading the project. To edit the ASP.NET Core project file, right-click on the project name in the Solution Explorer, and then select “Edit Project File” from the context menu. Once you click on the “Edit Project File” then the Project file will open in the Visual Studio editor itself.

5. Earlier, the .csproj file contained many GUIDs. But .Net Core now they are rarely used.



Use of .csproj File in .Net Core:

To compile and run the ASP.NET Core application, the compiler needs information such as the version of the .Net framework, the type of the application, the dependent library, etc. The .csproj file stores all this information that allows dotnet to build and compile the project. 

Upon running the ‘dotnet restore’ command, dotnet uses the .csproj file to determine the packages to install from NuGet.

The .chproj file contains the Target Framework which specifies the target framework for your application. To specify the target framework in the project file it is using something called Target Framework Moniker (TFM) like netcoreapp3.1 for .NET Core 3.1. It tells dotnet that it’s a web application that depends on what .Net framework version. 

In the ASP.Net project when we install a package using Nuget, the name of the package along with its version is listed in the .csproj file. The .csproj file is now used as a place where we manage the NuGet packages for your application.



Whenever we add any new packages into the application, then that package reference is also going to be added to the application project file.  Once you delete that package, then it will delete the reference from both the dependencies as well as from the project file.

The .chproj file also contains the project file and folder locations.

<?xml version="1.0" encoding="UTF-8"?>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
  <TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="SQLite" Version="3.13.0" />
  <PackageReference Include="Microsoft.Data.Sqlite.Core" Version="6.0.0-preview.4.21253.1" />
  <PackageReference Include="Microsoft.Extensions.Primitives" Version="6.0.0-preview.4.21253.7" />
  <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  <PackageReference Include="log4net" Version="2.0.12" />
</ItemGroup>
</Project>




Q067. What is wwwroot folder in ASP.NET Core? Why it is required?

In the traditional ASP.NET application, static files can be served from the root folder of an application or any other folder under it. But that is true in .Net Core. In ASP.Net core only those files that are in the wwwroot folder can be served over an HTTP request. All other files are blocked and cannot be served by default.

In the ASP.Net Core project by default, the wwwroot folder is treated as a web root folder. All the static files can be stored in any folder under the web root and accessed with a relative path to that root.

When you create an ASP.NET Core Web Application with Web and MVC Template, then by default this folder (wwwroot) is created in the root project folder. But if you create a new .NET Core Application with an Empty Template then by default this folder is not going to be created by Visual Studio.

You can create separate folders for the different types of static files such as JavaScript, CSS, Images, library scripts, etc. in the wwwroot folder. Then, the Static files can be stored in any folder under the webroot folder and can be accessed with a relative path to that root. 



You can access static files with the base URL and file name: 

http://domain:<port>/html/app.html

But remember, in order to access and serve the static files you need to include app.UseStaticFiles() middleware component in the ‘Configure()’ method of Startup.cs file

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. For example you can rename wwwroot folder to Content folder then you need to call the UseWebRoot() method to configure the MyWebRoot folder as a webroot folder in the Main() method of Program class:

var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot("Content")
            .UseIISIntegration()
            .UseStartup<MyStartup>()
            .Build();





Q068. How does ASP.NET Core serve static files? What is FileServer middleware in ASP.Net Core?

In ASP.Net all the static files are stored in the webroot folder called wwwroot folder by default. ASP.NET Core template provides a root folder called wwwroot which contains all these static files.

ASP.NET Core application cannot serve static files by default. We must include Microsoft.AspNetCore.StaticFiles middleware in the request pipeline. We do not need to install anything separately in ASP.NET Core 2.x application for it. But in ASP.NET Core 1.x application we need to install it from NuGget (Microsoft.AspNetCore.StaticFiles) separately.

After installing that we need to set UseStaticFiles() middleware inside Startup.Configure() enables the static files to be served to the client over HTTP. The UseStaticFiles() is an extension method included in the StaticFiles middleware so that we can easily configure it.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();       
}


The UseStaticFiles() middleware is an inbuilt middleware provided by ASP.NET Core Framework to handle the static files in an ASP.NET Core Application. After that you can use the static file:

http://domain:<port>/index.html



But if you want to serve files from the outside of the web root folder (wwwroot), then you need to specify the StaticFileOptions parameter in the UseStaticFiles method to serve the static file from outside the webroot folder:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "MyStaticFilesFolder")), 
RequestPath = "/StaticFiles"  
});      
}

The FileProvider option is used to specify the StaticFile folder from which static files will be served. The RequestPath option specifies the relative path in the URL which maps to the static folder. N

<img src="/StaticFiles/images/profile.jpg" class="img" alt="profile-image" />



But if you want to serve any default HTML file (index.html) on the root request, you need to call UseDefaultFiles() method before UseStaticFiles() in the Configure method.  Because we know that the order of middleware is very important. app.UseDefaultFiles() should be added before app.UseStaticFiles() in the request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();    
}

The UseDefaultFiles configures the DefaultFiles middleware which is a part of StaticFiles middleware. This will automatically serve the HTML file named default.html, default.htm, index.html, or index.htm on the HTTP request http://localhost:<port>. 

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFileServer();

app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World");
});
}




Q069. What are Configuration files? How does Application Configuration work in ASP.NET Core?

Configuration in ASP.NET Core is performed using one or more configuration providers. In ASP.NET Core the web.config files containing all the configuration parameters related to the application are all gone. Instead of that configuration and startup code are loaded from Startup.cs class at run time.

Configuration management in ASP.Net Core has improved significantly compared to how it was managed in the legacy .Net Framework. In .Net Core, it is saved as JSON instead of XML compared to the legacy .Net Framework. This makes reading and managing the configuration file extremely simple and user-friendly.

By default, the Visual Studio project template will create an appsettings.json and appsettings.Development.json file when a new project is created. These are the files where we save configurations based on the environment, where appsettings.json is the default configuration file. The environment name is usually available as an environment variable, with the key “ASPNETCORE_ENVIRONMENT”.



ASP.NET Core supports many methods of configuration. In ASP.NET Core, Configuration is implemented using various configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources at runtime:

  1. Settings files, such as appsettings.json
  2. Environment variables
  3. Azure Key Vault
  4. Azure App Configuration
  5. Command-line arguments
  6. Custom providers, installed or created
  7. Directory files
  8. In-memory .NET objects



Configuration System in ASP.NET Core is restructured compared to the traditional version of ASP.NET. The older version uses "System.Configuration" namespace and is able to read XML configuration files such as the web.config. The new configuration model in .Net Core can be accessed to the key/value-based settings and it can retrieve various sources, such as JSON, XML, and INI.

The ASP.NET Core web apps created with either dotnet new or Visual Studio create the WebApplication Builder with the default configuration:

var builder = WebApplication.CreateBuilder(args);



This initialized WebApplicationBuilder (builder) provides the default configuration for the app in the following order:

  1. ChainedConfigurationProvider that adds an existing IConfiguration as a source. 
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.{Environment}.json using the JSON configuration provider. 
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

Please note that the order matters here as well. The configuration providers that are added later override the previous key settings. Using the default configuration providers, the Command-line configuration provider overrides all other providers.




Q070. What is the default Configuration Files loading order in.Net Core? 

Configuration File Order:

The Order in which configuration files are loaded matters. If two configuration sources contain similar keys, the one which loads last wins. The configuration providers that are added later override the previous key settings. 

The default configuration loader loads the configuration in the following order:

  1. appsettings.json
  2. Environment-specific appsettings.{EnvironmentName}.json
  3. Environment variables
  4. Command-line parameters

So using the default configuration providers, the Command-line configuration provider overrides all other providers.




Q071. What are configuration JSON files in ASP.Net Core?  Why the web.config files are removed from the .Net Core?

In ASP.NET Core the web.config files containing all the configuration values related to the application are removed. Instead of that configurations and startup code are loaded from Startup.cs class at run time.

In .Net Core, all the configurations are saved as JSON instead of XML compared to the legacy .Net Framework. This makes it lightweight along with reading and managing the configuration file extremely simple and user-friendly.

ASP.Net Core is re-architected from traditional versions of standard ASP.net, where the configuration was relying on the System.Configuration and XML configurations in web.config file. 

In ASP.Net Core, a new easy way to declare and access the global settings for a solution, project-specific settings, client-specific settings, etc. The new configuration model works with XML, INI, and JSON files.



Q072. What are the different JSON Configuration files available in the ASP.Net Core project?

Below are the different JSON files available in the ASP.Net Core project:

json-config-files




1. global.json file: It defines solution-level configuration settings.
 
2. launchsettings.json: It defines 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 the compilation and debugging of specific profiles. 

3. appsettings.json: It is used to store custom application settings like connection strings, Logging etc.

4. bundleconfig.json: It is used to define the configuration for bundling and minification for the project. 

5. project.json: It contains all the project-level configuration settings 

6. bower.json:  Bower is a package manager for the web. Bower manages components that contain HTML, CSS, JavaScript, fonts, or even image files. Bower installs the right versions of the packages you need and their dependencies.

7. package.json:  The node.js modules are listed in package.json.




To Be Continued Part-08...


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.