Describe the ASP.NET Core.
ASP.NET Core is an open-source, cross-platform and high performance platform that allows you to build modern, Internet-connected and cloud enabled applications. With ASP.NET Core you can build web applications, IoT (Internet of things) apps, services and mobile Backends.
run on .NET Core.
You can do your development on Linux, Windows and MacOS.
deploy your code to cloud or on-premises.
What are the benefits of using ASP.NET Core over ASP.NET?
ASP.NET Core comes with the following benefits over ASP.NET.
Cross platform, provide ability to develop and run on Windows, Linux and MacOS.
Open-source
Unified Platform to develop Web UI and services.
Built-in dependency injection.
Ability to deploy on more than one server like IIS, Kestrel, Nginx, Docker, Apache etc
cloud enabled framework, provide support for environment based configuration systems.
Lightweight, High performance and modern HTTP request pipelines.
well suited architecture for testability
Integration of many client-side frameworks like Angular any version
Blazor allow you to use C# code in browser with JavaScript code.
What is the role of Startup class?
Startup class is responsible for configuration related things as below.
It configures the services which are required by the app.
It defines the app’s request handling pipeline as a series of middleware components.
// Startup class example
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// other middleware components
}
}
Startup class is specified inside the ‘Create Host Builder’ method when the host is created.
Multiple Startup classes can also be defined for different environments, At run time appropriate startup class is used.
Asp.net Core Interview Question
What is the role of Configure Services and Configure method?
Configure Services method is optional and defined inside startup class as mentioned in above code. It gets called by the host before the ‘Configure’ method to configure the app’s services.
Configure method is used to add middleware components to the Application Builder instance that’s available in Configure method. Configure method also specifies how the app responds to HTTP request and response.
Application Builder instance’s ‘Use…’ extension method is used to add one or more middleware components to request pipeline.
You can configure the services and middleware components without the Startup class and it’s methods, by defining this configuration inside the Program class in Create Host Builder method.
Describe the Dependency Injection.
Dependency Injection is a Design Pattern that’s used as a technique to achieve the Inversion of Control (IOC) between the classes and their dependencies.
ASP.NET Core comes with a built-in Dependency Injection framework that makes configured services available throughout the application. You can configure the services inside the Configure Services method as below.
services.AddScoped();
A Service can be resolved using constructor injection and DI framework is responsible for the instance of this service at run time.
What problems does Dependency Injection(DI) solve?
Let’s understand Dependency Injection with this C# example. A class can use a direct dependency instance as below.
Public class A {
MyDependency dep = new MyDependency();
public void Test(){
dep.SomeMethod();
}
}
But these direct dependencies can be problematic for the following reasons.
If you want to replace ‘My Dependency’ with a different implementation then the class must be modified.
It’s difficult to Unit Test.
If My Dependency class has dependencies then it must be configured by class. If Multiple classes have dependency on ‘My Dependency’, the code becomes scattered.
DI framework solves these problems as below:
Use Interfaces or base class to abstract the dependency implementation.
Dependencies are registered in the Service Container provided by ASP.NET Core inside Startup class ‘Configure Services’ method.
Dependencies are injected using constructor injection and the instance is created by DI and destroyed when no longer needed.
Advance Asp.net Core Interview Question
Describe the Service Lifetimes.
When Services are registered, there is a lifetime for every service. ASP.NET Core provide following lifetimes.
Transient – Services with transient lifetime are created each time they are requested from service container. So it’s best suited for stateless, light weight services.
Scoped – Services with scoped lifetime are created once per connection or client request. When using scoped service in middleware then inject the service via invoke or invokeAsync method. You should not inject the service via constructor injection as it treats the service behavior like Singleton.
Singleton – Service with singleton lifetime is created once when first time the service is requested. For subsequent requests same instance is served by service container.
Explain the Middleware in ASP.NET Core.
The Request handling pipeline is a sequence of middleware components where each component performs the operation on request and either call the next middleware component or terminate the request. When a middleware component terminates the request, it’s called Terminal Middleware as It prevents next middleware from processing the request. You can add a middleware component to the pipeline by calling .Use… extension method as below.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
So Middleware component is program that’s build into an app’s pipeline to handle the request and response. Each middleware component can decide whether to pass the request to next component and to perform any operation before or after next component in pipeline.
What is Request delegate?
Request delegates handle each HTTP request and are used to build request pipeline. It can configured using Run, Map and Use extension methods. An request delegate can be a in-line as an anonymous method (called in-line middleware) or a reusable class. These classes or in-line methods are called middleware components.
Asp.net Core Interview Question
What is Host in ASP.NET Core?
Host encapsulates all the resources for the app. On startup, ASP.NET Core application creates the host. The Resources which are encapsulated by the host include:
HTTP Server implementation
Dependency Injection
Configuration
Logging
Middleware components
Describe the Generic Host and Web Host.
The host setup the server, request pipeline and responsible for app startup and lifetime management. There are two hosts:
.NET Generic Host
ASP.NET Core Web Host
.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 backwards compatibility.
Describe the Servers in ASP.NET Core.
Server is required to run any application. ASP.NET Core provides an in-process HTTP server implementation to run the app. This server implementation listen for HTTP requests and surface them to the application as a set of request features composed into an Http Context.
ASP.NET Core use the Kestrel web server by default. ASP.NET Core comes with:
Default Kestrel web server that’s cross platform HTTP server implementation.
IIS HTTP Server that’s in-process server for IIS.
HTTP.sys server that’s a Windows-only HTTP server and it’s based on the HTTP.sys kernel driver and HTTP Server API.
Advance Asp.net Core Interview Question
How Configuration works in ASP.NET Core?
In ASP.NET Core, Configuration is implemented using various configuration providers. Configuration data is present in the form of key value pairs that can be read by configuration providers as key value from different configuration sources as below.
app settings .json – settings file
Azure Key Vault
Environment variables
In-memory .NET objects
Command Line Arguments
Custom Providers
By default apps are configured to read the configuration data from appsettings.json, environment variables, command line arguments etc. While reading the data, values from environment variables override appsettings.json data values. ‘Create Default Builder’ method provide default configuration.
How to read values from App settings.json file?
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 load the values from appsettings.json and then from appsettings.Environment.json file.
Environment specific values override the values from appsettings.json file. In development environment appsettings.Development.json file values override the appsettings.json file values, same apply to production environment.
What is the Options Pattern in ASP.NET Core?
Options Pattern allow you to access related configuration settings in Strongly typed way using some classes. When you are accessing the configuration settings with the isolated classes, The app should adhere these two principles.
Interface Segregation Principle (ISP) or Encapsulation: The class the depend on the configurations, should depend only on the configuration settings that they use.
Separation of Concerns: Settings for different classes should not be related or dependent on one another.
Asp.net Core Interview Question
How to use multiple environments in ASP.NET Core?
ASP.NET Core use environment variables to configure application behavior based on runtime environment. launch Settings .json file sets ASPNETCORE_ENVIRONMENT to Development on local Machine.
How Routing works in ASP.NET Core?
Routing is used to handle incoming HTTP requests for the app. Routing find matching executable endpoint for incoming requests. These endpoints are registered when app starts. Matching process use values from incoming request url to process the requests. You can configure the routing in middleware pipeline of configure method in startup class.
app.UseRouting(); // It adds route matching to middlware pipeline
// It adds endpoints execution to middleware pipeline
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
How to handle errors in ASP.NET Core?
ASP.NET Core provides a better way to handle the errors in Startup class as below.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
For development environment, Developer exception page display detailed information about the exception. You should place this middleware before other middleware’s for which you want to catch exceptions. For other environments Use Exception Handler middleware loads the proper Error page.
You can configure error code specific pages in Startup class Configure method as below.
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Request.Path = "/not-found";
await next();
}
if (context.Response.StatusCode == 403 || context.Response.StatusCode == 503 || context.Response.StatusCode == 500)
{
context.Request.Path = "/Home/Error";
await next();
}
});
Advance Asp.net Core Interview Question
How ASP.NET Core serve static files?
In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are the served directly to the clients. ASP.NET Core template provides a root folder called www root which contains all these static files. UseStaticFiles() method inside Startup. Configure enables the static files to be served to client.
You can serve files outside of this web root folder by configuring Static File Middleware as following.
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
Explain Session and State management in ASP.NET Core
As we know HTTP is a stateless protocol. HTTP requests are independent and does not retain user values. There are different ways to maintain user state between multiple HTTP requests.
Cookies
Session State
Temp Data
Query strings
Hidden fields
Http Context. Items
Cache
Can ASP.NET Application be run in Docker containers?
Yes, you can run an ASP.NET application or .NET Core application in Docker containers.
Asp.net Core Interview Question
Explain the Caching or Response caching in ASP.NET Core.
Caching significantly improves the performance of an application by reducing the number of calls to actual data source. It also improves the scalability. Response caching is best suited for data that changes infrequently. Caching makes the copy of data and store it instead of generating data from original source.
Response caching headers control the response caching. Response Cache attribute sets these caching headers with additional properties.
What is In-memory cache?
In-memory cache is the simplest way of caching by ASP.NET Core that stores the data in memory on web server.
Apps running on multiple server should ensure that sessions are sticky if they are using in-memory cache. Sticky Sessions responsible to redirect subsequent client requests to same server. In-memory cache can store any object but distributed cache only stores byte[].
I Memory Cache interface instance in the constructor enables the In-memory caching service via ASP.NET Core dependency Injection.
What is Distributed caching?
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 instance from any constructor enable distributed caching service via Dependency Injection.
Advance Asp.net Core Interview Question
What is XSRF or CSRF? How to prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core?
Cross-Site Request Forgery (XSRF/CSRF) is an attack where attacker that acts as a trusted source send some data to a website and perform some action. An attacker is considered a trusted source because it uses the authenticated cookie information stored in 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 Form Tag helper automatically inject the anti forgery tokens into HTML form element.
You can add manually anti forgery token in HTML forms by using @Html.AntiForgeryToken() and then you can validate it in controller by Validate Anti Forgery Token() method.
What is the Area?
Area is used to divide large ASP.NET MVC application into multiple functional groups. In general, for a large application Models, Views and controllers are kept in separate folders to separate the functionality. But Area is a MVC structure that separate an application into multiple functional groupings. For example, for an e-commerce site Billing, Orders, search functionalities can be implemented using different areas.
Explain the Filters?
Filters provide the capability to run the code before or after the specific stage in request processing pipeline, it could be either MVC app or Web API service. Filters performs the tasks like Authorization, Caching implementation, Exception handling etc. ASP.NET Core also provide the option to create custom filters. There are 5 types of filters supported in ASP.NET Core Web apps or services.
Authorization filters run before all or first and determine the user is authorized or not.
Resource filters are executed after authorization. On Resource Executing filter runs the code before rest of filter pipeline and On Resource Executed runs the code after rest of filter pipeline.
Action filters run the code immediately before and after the action method execution. Action filters can change the arguments passed to method and can change returned result.
Exception filters used to handle the exceptions globally before writing the response body
Result filters allow to run the code just before or after successful execution of action results.
Asp.net Core Interview Question
Describe the ASP.NET Core MVC?
ASP.NET Core MVC is a framework to build web applications and APIs. It’s based on Model-View-Controller (MVC) Design Pattern. This design pattern separate an application into three main components known as Model, View and Controller. It also helps to achieve SoC (Separation of Concern) design principle.
ASP.NET Core MVC is light weight, open-source and testable framework to build web applications and services.
What are the features provided by ASP.NET Core?
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 Web Socket and Signal R
Provide protection against CSRF (Cross-Site Request Forgery)
What are the advantages of ASP.NET Core over ASP.NET?
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
Advance Asp.net Core Interview Question
What is Meta packages?
The framework .NET Core 2.0 introduced Meta package 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. Asp Net Core. All is a meta package provide by ASP.NET core.
Can ASP.NET Core application work with full .NET 4.x Framework?
Yes. ASP.NET core application works with full .NET framework via the .NET standard library.
What is the startup class in ASP.NET core?
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 class name must “Startup”, it can be anything, we can configure startup class in 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>();
}
Asp.net Core Interview Question
What is the use of Configure Services method of startup class?
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.
What is the use of the Configure method of startup class?
It defines how the application will respond to each HTTP request. We can configure the request pipeline by configuring the middleware. It accepts IApplication Builder as a parameter and also it has two optional parameters: IHosting Environment and ILogger Factory. Using this method, we can configure built-in middleware such as routing, authentication, session, etc. as well as third-party middleware.
What is middleware?
It is software which is injected into the application pipeline to handle request and responses. They are just like chained to each other and form as a pipeline. The incoming requests are passes through this pipeline where all middleware is configured, and middleware can perform some action on the request before passes it to the next middleware. Same as for the responses, they are also passing through the middleware but in reverse order.
Advance Asp.net Core Interview Question
What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.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. The middleware adds using IApplicationBuilder.Use may call the next middleware in the pipeline whereas the middleware adds using IApplicationBuilder.Run method never calls the subsequent ore next middleware. After IApplicationBuilder.Run method, system stop adding middleware in request pipeline.
What is the use of “Map” extension while adding middleware to ASP.NET Core pipeline?
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.
public void Configure(IApplicationBuilder app)
{
app.Map("/path1", Middleware1);
app.Map("/path2", Middleware2);
}
What is routing in ASP.NET Core?
Routing is functionality that map incoming request to the route handler. The route can have values (extract them from URL) that used to process the request. Using the route, routing can find route handler 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 request with route handler and Generate URL that used in response. Mostly, the application having a single collection of routes and this collection are used for the process the request. The Route Async method is used to map incoming request (that match the URL) with available in route collection.
Asp.net Core Interview Question
How to enable Session in ASP.NET Core?
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();
….
….
}
}
What are the various JSON files available in ASP.NET Core?
There are following JSON files in ASP.NET Core :
global.json
launch settings.json
app settings.json
bundle config.json
bower.json
package.json
What is tag helper in ASP.NET Core?
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">
Advance Asp.net Core Interview Question
How to disable Tag Helper at element level?
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>
What are Razor Pages in ASP.NET Core?
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 feature 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 handle request directly without passing through the controller. The Razor pages may have code behind file, but it is not really code-behind file. It is class inherited from Page Model class.
How can we do automatic model binding in Razor pages?
The Razor pages provide the option to bind property automatically when posted the data using Bind Property attribute. By default, it only binds the properties only with non-GET verbs. we need to set Supports Get property to true to bind a property on getting request.
Example
public class Test1Model : PageModel
{
[BindProperty]
public string Name { get; set; }
}
Asp.net Core Interview Question
How can we inject the service dependency into the controller?
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;
}
}
How to specify service lifetime for register service that added as a dependency?
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 the cleaning these dependencies, it will take care by ASP.NET Core framework. There is three type 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 Add Singleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request 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>();
What are some benefits of ASP.NET Core over the classic ASP.NET?
Cross-Platform: The main advantage of ASP.NET Core is that it’s not tied to a Windows operating system, like the legacy ASP.NET framework. You can develop and run production-ready ASP.NET Core apps on Linux or a Mac. Choosing an open-source operating system like Linux results in significant cost-savings as you don’t have to pay for Windows licenses.
High Performance: It’s also designed from scratch, keeping performance in mind. It’s now one of the fastest web application frameworks.
Open Source: Finally, it’s open-source and actively contributed by thousands of developers all over the world. All the source code is hosted on GitHub for anyone to see, change and contribute back. It has resulted in significant goodwill and trust for Microsoft, notwithstanding the patches and bug-fixes and improvements added to the framework by contributors worldwide.
New Technologies: With ASP.NET Core, you can develop applications using new technologies such as Razor Pages and Blazor, in addition to the traditional Model-View-Controller approach.
Advance Asp.net Core Interview Question
When do you choose classic ASP.NET over ASP.NET Core?
Though it’s a better choice in almost all the aspects, you don’t have to switch to ASP.NET Core if you are maintaining a legacy ASP.NET application that you are happy with and that is no longer actively developed.
ASP.NET MVC is a better choice if you:
Don’t need cross-platform support for your Web app.
Need a stable environment to work in.
Have nearer release schedules.
Are already working on an existing app and extending its functionality.
Already have an existing team with ASP.NET expertise.
Why Use ASP.NET Core for Web Application Development?
ASP.NET Core is an robust, and feature-rich framework that provides features to develop super-fast APIs for web apps. ASP.NET Core should be preferred for following reason:
ASP.NET Core is faster compare to traditional ASP.NET.
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.
Flexible deployment: Can be included in your app or installed side-by-side user or machine-wide. Runs on IIS or can be self-hosted in your own process.
Built-in support for dependency injection.
ASP.NET Core is cloud-ready and has improved support for cloud deployment.
Provides Support for Popular JavaScript Frameworks.
Unification Of Development Models which allows the MVC and Web API development models to use the same base class Controller.
Razor Pages makes coding page-focused scenarios easier and more productive.
Environment based configuration supported for cloud deployment.
Built in logging support.
In ASP.NET we had modules and handlers to deal with requests. In ASP.NET Core we have middleware which provides more control how the request should be processed as they are executed in the order in which they are added.
What Is The Purpose Of Webhost builder() Function?
It is use to build up the HTTP pipeline via web Host Builder. Use() chaining it all together with Web Host Builder. Build() by using the builder pattern. It is available within the Microsoft .Asp Net. Hosting namespace. The purpose of the Build method is to build the required services and a Microsoft. AspNetCore.Hosting. IWeb Host which hosts a web application.
Asp.net Core Interview Question
What Is The Purpose Of Configure services In Asp.net Core 1.0?
Configure Services defines the services used by the application like ASP.NET MVC Core framework, Entity Framework Core, CORS, Logging, Memory Caching etc.
E.g.
public void Configure Services(IService Collection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
Explain The Purpose Of Configure Method?
Configure method defines the middleware in the Http request pipeline. The software components that are assembled into an application pipeline to handle requests and responses are the middleware’s.
E.g.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ loggerFactory.AddConsole(Configuration.GetSection(“Logging”));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: “default”,
template: “{controller=Home}/{action=Index}/{id?}”);
});
}
In the above code,UseExceptionHandler is a middleware. It is added as a middleware to the pipeline that will catch exceptions, log them, reset the request path, and re-execute the request.
What Is The Purpose Of Add singleton Method?
The AddSingleton method, adds a singleton service of the type specified in TService with an implementation type specified in TImplementation to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. It returns a reference to this instance after the operation has completed.
The general syntax is
public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services)
where TService : class
where TImplementation : class, TService;
Services can be registered with the container in several ways. In this case we are using Singleton Service by using the Add Singleton<iServices, Service>() method. Singleton lifetime services are created the first time they are requested and then every subsequent request will use the same instance. If the application requires singleton behavior, allowing the services container to manage the service’s lifetime is recommended instead of implementing the singleton design pattern and managing the object’s lifetime in the class.
e.g.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
}
Advance Asp.net Core Interview Question
What Is Transfer-encoding?
The encoding used to transfer the entity to the user. It is set to Chunked indicating that Chunked transfer encoding data transfer mechanism of the Hypertext Transfer Protocol (HTTP) is initiated in which data is sent in a series of “chunks”.
What Is X-source files?
It is the custom header. It contains the base64-encoded path to the source file on disk and is used to link a page’s generated output back to that source file. It’s only generated for localhost requests.
How To Scaffold Model From Existing Database In Asp.net MVC Core?
To scaffold models from existing database in ASP.NET MVC Core, go to Tools –> NuGet Package Manager –> Package Manager Console
Now execute following command:
Scaffold-dB Context “Server=datbase-PC;Database=TrainingDatabase;Trusted_Connection=True;MultipleActiveResultSets=true;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
If you get an error “The term ‘Scaffold-DbContext’ is not recognized as the name of a cmdlet” , simply Close the Visual Studio and open again.
This creates .cs files related with all database tables into Models folder of your project. This also creates a database context (in this case the name will be Training Database Context. cs as the database name is Training Database).
Asp.net Core Interview Question
What are the different languages supported by .NET Core?
C#, Visual Basic, and F# languages can be used to write applications and libraries for .NET Core. These languages can be used in your favorite text editor or Integrated Development Environment (IDE), including:
· Visual Studio· Visual Studio Code· Sublime Text· Vim
What are the different components of .NET Core?
.NET Core is composed of the following parts:
· The .NET Core runtime, which provides a type system, assembly loading, a garbage collector, native interop, and other basic services.
· .NET Core framework libraries provide primitive data types, app composition types, and fundamental utilities.
· The ASP.NET runtime, which provides a framework for building modern cloud-based internet connected applications, such as web apps, IoT apps, and mobile backends.
· The .NET Core CLI tools and language compilers (Roslyn and F#) that enable the .NET Core developer experience.
· The dot net tool, which is used to launch .NET Core apps and CLI tools. It selects the runtime and hosts the runtime, provides an assembly loading policy, and launches apps and tools.
These components are distributed in the following ways:
· .NET Core Runtime — includes the .NET Core runtime and framework libraries.
· ASP.NET Core Runtime — includes ASP.NET Core and .NET Core runtime and framework libraries.
· .NET Core SDK — includes the .NET CLI Tools, ASP.NET Core runtime, and .NET Core runtime and framework.
What are the differences between .NET Core Runtime and SDK?
The SDK contains everything that are required for developing a .NET Core application easily, such as the CLI and a compiler. Whereas, the Runtime is the “virtual machine” that hosts/runs the application and abstracts all the interaction with the base operating system.
Advance Asp.net Core Interview Question
Explain why to choose ASP.NET Core?
Millions of developers have used (and continue to use) ASP.NET 4.x to create web apps. ASP.NET Core is a redesign of ASP.NET 4.x, with architectural changes that result in a leaner, more modular framework.
ASP.NET Core provides the following benefits:
· A unified story for building web UI and web APIs.
· Architected for testability.
· Razor Pages makes coding page-focused scenarios easier and more productive.
· Blazor lets you use C# in the browser alongside JavaScript. Share server-side and client-side app logic all written with .NET.
· Ability to develop and run on Windows, macOS, and Linux.
· Open-source and community-focused.
· Integration of modern, client-side frameworks and development workflows.
· Support for hosting Remote Procedure Call (RPC) services using gRPC.
· A cloud-ready, environment-based configuration system.
· Built-in dependency injection.
· A lightweight, high-performance, and modular HTTP request pipeline.
· Ability to host on the following:
· Kestrel
· IIS
· HTTP.sys
· Nginx
· Apache
· Docker
· Side-by-side versioning.
· Tooling that simplifies modern web development.