ASP.Net Core important interview questions and answers

In this blog, I have collected interview questions and answers of ASP.Net Core. Below are few important ASP.Net Core interview questions and answers which are helpful in interview preparation.


1. What is ASP.Net Core?

The ASP.Net Core is a new open-source framework introduced by Microsoft. ASP.Net Core is a cross-platform open-source framework for building modern applications including cloud-based development.

Features of ASP.Net Core

  • Develop cross platform application
  • Fast
  • Use of Razor pages
  • Dependency Injection

2. Benefits of .Net Core?

  • It is a framework to build web applications
  • It is open source
  • Deploy .Net core application to on-premises or to the cloud.
  • Build and run the application on Windows, MAC, and Linux
  • A cloud-ready environment
  • Ability to host in IIS or self-host

3. ASP.Net vs ASP.Net Core

ASp.Net Core is the latest version of ASP.Net framework and along with that ASP.Net Core is an open-source and cross platform framework which gives you privilege to develop modern web based and windows based application. ASP.Net based application can run on windows machine only.But, the application developed in .Net Core is not bounded with any environment, you are free to host .Net Core based application on Windows, Mac or Linux machine. Note: No more ASPX pages in ASP.Net Core.

4. Versions of ASP.Net Core

Below table tells you the version details of ASP.Net Core (till July 2020) and their Long term support.

VersionReleasedLong Term Support
.Net Core 3.1December, 2019Yes
.Net Core 3.0September, 2019No
.Net Core 2.2December, 2018No
.Net Core 2.1May, 2018Yes
.Net Core 2.0August, 2017No
.Net Core 1.1November, 2016No
.Net Core 1.0June, 2016No

5. What is Kestrel?

Kestrel is a default web server used in ASP.Net Core application. Kestrel is a light-weight and cross platform web server. It supports SSL and doesn't have advance features like IIS as it is a light-weight web server. It is included in Project.json file -

        <'PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
To install this through package manager, use below command -
Install-Package Microsoft.AspNetCore.Server.Kestrel -Version 2.2.0

6. What is Startup.cs file in ASP.Net Core?

ASP.Net Core project includes Startup.cs file which gets executed as soon as applications gets started. It contains a ConfigureServices() and Configure() method which gets called by the eruntime. We can get defined database connection string in this method with the help of IServiceCollection. ConfigureServices() is the method that we use to configure services required for our application. Below is the ConfigureServices() method in startup.cs file -

     public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

Below is the Config() method in startup.cs file -

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
         }

7. How to define URL rewriting in ASP.Net Core?

An url redirection and rewriting task can be done in Configure() method of startup.cs file in ASP.Net Core. Below is the syntaxt to redirect

app.Use(async (context, next) =>
            {
                var url = context.Request.Path.Value;
                if (url.Contains("/old-page-url"))
                {
                    // rewrite and continue processing
                    context.Response.Redirect("/new-page-url",true);
                    return;
                }
               await next();
            });
In context.Response.Redirect, if you passed second parameter as true then your redirect will work as permanent redirect with 301 as HTTP status, which helps you in Search Engine Optimization (SEO).

8. AddSingleton() vs AddTransient() vs AddScope() in ASP.Net Core

All these 3 methods are very important in ASP.Net Core, they have there own significance of using in your application. Also, this is on of the most important ASP.Net Core interview question. Let's see them one by one.

AddSingleton() Method

In AddSingleton() method, only one instance of service is created, when the service is executed at very first time. So, a single instance is created for a service , no matter how many times the service is being executed.

AddTransient() Method

With AddTransient() method, it creates new instance every time a service request is raised, doesn't matter it is in the same HTTP request or different HTTP request.

AddScope() Method

With AddScope() method, we get new instance with different http requests. But we get same instance if it is within the same scope.

We use these methods in ConfigureServices() method in startup.cs file
        public void ConfigureServices(IServiceCollection services)
        {
         services.AddSingleton<'IProductRepository, ProductRepository'>();
    }

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddTransient<'IProductRepository, ProductRepository'>();
        }

        public void ConfigureServices(IServiceCollection services)
        {
        services.AddScoped<'IProductRepository, ProductRepository'>();
            }

9. Explain ASP.Net Core Middleware

Middleware is a componentwhich gets executed every time a request is made to the ASP.Net Core application. Middleware is similar to HttpHandlers and HttpModules of traditional ASP.Net. In ASP.Net Core, Request delegates are used to build the request pipeline to handle each and every HTTP request. Request delegates can be configured using Run(), Map() or Use() extension methods. We can use these methods in Configure() method of startup.cs file

Run() Method

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hey There...");
        });
    }
}

Use() Method

For eg - If you want to redirect your one of old page to the new page, then you have to check each http request to match the UTL containing your old page url and then redirect to new page.
 app.Use(async (context, next) =>
            {
                var url = context.Request.Path.Value;
  if (url.Contains("/old-page-url"))
                {
                    context.Response.Redirect("/new-page-url",true);
                    return;
                }
   await next();
            });

10. Dependency Injection in ASP.Net Core

Dependency Injection, is a design approach, which helps to create loosely coupled code. In another way, we can say that Dependency Injection is used to remove dependency between two classes and helps to create independent classes. To use Dependency Injection in ASP.Net Core,use AddScoped<>() or AddTransient<>() or AddSingleton<>() methods in ConfigureServices() method in startup.cs file

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<'IUserSingleton, UserSingleton>();
    services.AddScoped<'IProductRepository, ProductRepository>();
    services.AddTransient<'IMyClassTransient, MyClassTransient>();
}

11. What is Razor Pages?

Razor pages are the next evolution of traditional ASP.Net WebForms. File extension of razor pages is .cshtml ASP.Net Core Razor Page is very similar to ASP.NET MVC's view pages. It has a similarity in syntax and functionality as MVC. The major difference is that in an MVC application model and controller code is included or bonded with View pages. Razor Pages vs MVC in .Net Core

12. Database connection string in ASP.Net Core

A database connection string is a very basic task for a developer. But defining a database connection string in .Net Core and reading back into C# code is a little different than the traditional ASP.Net framework. In .Net core, we don't have web.config like ASP.Net framework. In ASP.Net Core we have JSON based file to manage database connection string.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=Test;Trusted_Connection=Yes;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
If you are using entity framework core then, get the connection name in ConfigureServices() method defined in startup.cs file.
 services.AddDbContext(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
In general, use below code to read and use database connection string defined in appsettings.json file
var dbconfig = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();
if (!string.IsNullOrEmpty(dbconfig.ToString()))
                {
                    string dbconnectionStr = dbconfig["ConnectionStrings:DefaultConnection"];
                }

13. Routing in ASP.Net Core

Routing is a mechanism to match incoming HTTP request and then tranfer those request to matching endpoint URL. You will find a defined route in startup.cs file when you create an ASP.Net Core project. In Configure() method, below is the pre-defined routing

  app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
You can define attribute routing in Controller class of ASP.Net Core application -
        [HttpGet("/my-dashboard")]
        public IActionResult Dashboard()
        {
            var listData = _context.DashboardData.OrderBy(x=>Guid.NewGuid()).ToList().Take(10);
            return View(listData);
        }

14. wwwroot folder in .Net Core

wwwroot folder in ASP.Net Core application contains static files for eg images, stylesheets, script files. It is treated as root folder of .Net Core web application.

15. What is tag helper in ASP.Net Core?

Tag Helpers helps server side code to create and render HTML tags in Razor View engine. Tag Helpers do the same thing as HTML Helpers does in previous versions of MVC but with a variety of changes. Tag Helpers enable IntelliSense, which allow to build HTML markup in easy way. Tag Helpers in ASP.Net Core

Hope these ASP.Net Core interview questions and answers are helpful to you. Please share this within your community and comment below in case you have any feedback.

Comments