ASP.NET Core Interview Questions and Answers (12) - Page 1

What are the advantages of the inclusion of Nuget Packages in Asp.net Core 1.0?

The inclusion of Nuget Packages will make the applications to be optimized as we need to include only those packages that we need. The benefits includes

- Better performance gain
- Secured Application
- Improved and reduced servicing
- Pay for what you use model
- Lightweight
What is ASP.NET Core 1.0?

Asp.net Core1.0 is the next version of Asp.net which is 5.0. It is open source and cross-platform framework (supports for Windows, Mac and Linux) suitable for building cloud based internet connected applications like web apps, IoT apps and mobile apps.Asp.net Core has made itself independent of System.Web.dll and is heavily based on the modular NuGet packages.
What is the purpose of WebHostBuilder() function?

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

UseIISIntegration configures the port and base path the server should listen on when running behind AspNetCoreModule. The app will also be configured to capture startup errors. WebHostBuilder uses the UseIISIntegration for hosting in IIS and IIS Express.
In Asp.net Core 1.0, the Program.cs file looks as under using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace Example1 { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } } Explain it.

The Main() method uses WebHostBuilder(). It is use to build up the HTTP pipeline via webHostBuilder.Use() chaining it all together with WebHostBuilder.Build() by using the builder pattern. It is available within the Microsoft.AspNet.Hosting namespace.The purpose of the Build method is to build the required services and a Microsoft.AspNetCore.Hosting.IWebHost which hosts a web application.The web hosting environment uses Kestrel, a cross-platform web server. UseContentRoot specifies the content root directory to be used by the web host.UseIISIntegration configures the port and base path the server should listen on when running behind AspNetCoreModule. The app will also be configured to capture startup errors. WebHostBuilder uses the UseIISIntegration for hosting in IIS and IIS Express. UseStartup specifies the startup type to be used by the web host. The Startup class is the place where we define the request handling pipeline and where any services needed by the app are configured. The Startup class must be public. The Build and Run methods build the IWebHost that will host the app and start it listening for incoming HTTP requests.
What is the purpose of ConfigureServices in ASp.net Core 1.0?

ConfigureServices defines the services used by the application like ASP.NET MVC Core framework, Entity Framework Core, CORS,Logging, MemoryCaching etc.
E.g.

public void ConfigureServices(IServiceCollection 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 middlewares.

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 UseDeveloperExceptionPage()?

This method belongs to the Microsoft.AspNetCore.Builder namespace of DeveloperExceptionPageExtensions static class. The purpose of this function is to capture synchronous and asynchronous System.Exception instances from the pipeline and generates HTML error responses. It returns a reference to the app after the operation is completed.We use the UseDeveloperException() extension method to render the exception during the development mode.
What is the purpose of AddSingleton 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 AddSingleton<IService, 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>();
}

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-SourceFiles?

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-DbContext "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 TrainingDatabaseContext.cs as the database name is TrainingDatabase).
Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Interview Questions and Answers Categories