• 1. What are the new features in Asp.net Core when compare with the Asp.Net Framework?


    - Support cross-platform, you can deploy in the window, Linux.

    - Support docker to deploy the application.

    - Razor page engine.

    - Support default Dependency Injection.

    - Support SignalR + Websocket.

    - Best performance.

    - Support the Single Page Application template (SPA with Angular).

  • 2. What is the ViewComponent in Asp.net core?


    The View component in Asp.net core very likes a partial view in the Asp.net framework. It is a new point be introduced in Asp.Net core but it powerful than a partial view. View components don't use model binding, and it only depends on the data provided when calling into it.

    A view component:

    - Renders a chunk rather than a whole webpage.
    - It separates with two parts that include a controller business code and a view HTML code.
    - Can have parameters and code business logic.
    - Is typically invoked from a page.

    For example, I'll create a view component to display menu navigation for a webpage.

    Step 1: Create a Controller business code (HeaderViewComponent.cs)

     public class HeaderViewComponent : ViewComponent
        // Step 1. Initial all services with DI 
        private IProgLanguageCached _languageCached;
        public HeaderViewComponent(IProgLanguageCached languageCached)
            _languageCached = languageCached;
       // Step 2. Write business code will return to view in InvokeAsync method
        public async Task<IViewComponentResult> InvokeAsync()
            var result = new List<ProgLanguageModel>();
            var model = await _languageCached.GetHighlight();
            if(model != null && model.Any())
                result = model.Select(x => new ProgLanguageModel(x)).ToList();
            return View(result);

    Step 2: View binding code (Shared/Components/Header/Default.cshtml)

     @using QDM.App.Model
    @model List<ProgLanguageModel>
    <div class="pull-left full-width">
        <div class="container">
            <div class="menu-align full-width pull-left">
                    <div class="display-ib first-item">
                        <ul class="menu menu-left">
                            @if (Model != null && Model.Any())
                                foreach (var language in Model)
                                        <a href="@language.DetailUrl">@language.ShortName</a>

    Step 3: Call view component any view page you want

      @await Component.InvokeAsync("Header") 
  • 3. What is the Startup class in ASP.NET core?


    Startup class is an important class because it configures services and the app's request pipeline. This class only runs one time when starting the application.

    This class includes three parts:

    - Startup() constructor: You can load & initial all JSON & config file here.

    ConfigureServices() method: This method gets called by the runtime. Use this method to add services to the container. 

    Configure() method: This method to create the app's request processing pipeline.

    * Note: This class is called in Program.cs when starting the application.

  • 4. What is the difference between ConfigureServices() and Configure() methods in Startup class?


    You can read again the answer to question 3.

    1. ConfigureServices()

    This method is used to add/register services to the container.  You can add authentication, cookies login, session, register Dependency injection for all services,  config cross domain, add localization ... 

    For example : 

     public void ConfigureServices(IServiceCollection services)
        // Init and set timeout session
        services.AddSession(options =>
            options.IdleTimeout = TimeSpan.FromHours(AppSettingsModel.JWTConfiguration.ExpiredTime);
        // Add version support for asp.net core
        //Configure Identity
        //Configure Identity
        services.Configure<IdentityOptions>(options =>
            // Password settings
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 6;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(AppSettingsModel.JWTConfiguration.ExpiredTime);
            options.Lockout.MaxFailedAccessAttempts = 10;
            // User settings
            options.User.RequireUniqueEmail = true;
        // Register dependency injection for some services.
        services.AddTransient<IRazorViewEngine, CustomRazorViewEngine>();

    2. Configure() 

    This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    This method will contain much middleware to help filter all HTTP request pipeline, each middleware has its own function. Asp.net core also provided some built-in middleware and you also can make a custom middleware to listen and check something by each request.

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        if (env.IsDevelopment())
        // Configure listening route for site
        app.UseEndpoints(endpoints =>
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
  • 5. What is the middleware in Asp.net core? When should we use it? Please provide some examples.


    The middleware is a new feature and introduced in Asp.net core, it is very important to process or filter request and response to end-user. Middlewares are software components that are assembled into an application pipeline to handle requests and responses. You can understand easily middleware looks like a net help filter or process something business code before request or response. You can use middleware to cache page, logging, authentication, cache static file, etc ...

    A middleware includes two parts, they are request logic code and response logic code.  it is not required all, it depends on your business. 

    Two parts are separated by the next() function, above this function is for request and under is for the response.

    Middleware in asp.net core

    Middleware will be registered inside the Configure() function of Startup class. Asp.net core also provided many middleware build-in available for you such as UseHttpsRedirection(), UseStaticFiles(), UseRouting(), UseCors(), UseAuthentication(), etc ... and you also make a custom middleware for you business.

    For example, I will make a middle to log some information about branch:

     public void Configure(IApplicationBuilder app)
        // This is a middleware
        app.Use(async (context, next) =>
            //START code for request
            var branchVer = context.Request.Query["branch"];
            _logger.LogInformation("Branch used = {branchVer}", branchVer);
            //END code for request
            await next();
            //START code for response
            //  Do something here 
            //END code for response
  • 6. What is the purpose of the IHostingEnvironment interface in ASP.NET Core?


    The IHostingEnvironment interface help provides information about the web hosting environment an application is running in. I usually this interface to get the content root path and get the current environment mode of application.

    For example, when the application starts I want load appsetting.json file to read some config keys, I can set up as below code in the constructor of Startup.css :

     public Startup(IHostingEnvironment evm)
        var builder = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json", true, true)
          .AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
        Configuration = builder.Build();
  • 7. What is the difference between ViewBag and ViewData in Asp.Net core?


    - ViewData and ViewBag are used for the same purpose, they use to transfer data from controller to view.

    - Viewbag derives from DynamicViewData so it allows create dynamic properties and you no need to cast data. ViewBag not support any function for add, remove, update or clear.

    - ViewData derives from ViewDataDictionary, so it supports some method useful such as ContainsKey, Add, Remove and Clear, Have a point important need remember that ViewData is not auto-cast data so you need to cast before use and have to check null.

  • 8. What is the wwwroot folder? When do we need to use it?


    This folder used to store all static files such as image, video, audio, css, js, HTML static file... This also is a root folder of the application when the application running. 

  • 9. How to read the appsettings.json file in Asp.net core? 


    To read appsettings.json file in asp.net core, we need to load the JSON file when the application starts.  IConfiguration interface will help read appsettings.json file when it loaded. For more detail, you can read the article Best way to read appsettings.json file in ASP.NET Core.

  • 10. How to configure environment mode in Asp.net Core?


    To configure envỉonment mode in a project of Asp.net core, we have two steps :

    Step 1: Create JSON file with .mode-evm extension.

    For example, my project has 3 models are development, testing and product, I will create more three files the same with three models. They look like :

      - appsettings.json
     |  -- appsettings.Development.json
     |  -- appsettings.Testing.json
     |  -- appsettings.Product.json 

    Read configure value in asp.net core

    Step 2: Setting the environment variable for the project.

    If you are coding and run in local you can select the project from Solution Explorer panel and press Alt + Enter or right-click the project and select Properties option.
    From the Debug tab, you will see the environment variables with Name/value. You can change the value here.

    Read configure value in asp.net core

  • 11. What is the Tag Helper in Asp.net Core?


    Tag Helper is a new feature introduced in Asp.net core. Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files, It looks like Html helper in Asp.net Framework MVC.

    This feature is available in ASP.NET Core 2.0 or later, Asp.net core support many built-in tags server-side and you also create a custom tag. For example :

     @model RegisterAddressViewModel
    <form asp-controller="Demo" asp-action="RegisterAddress" method="post">
        Email:  <input asp-for="Email" /> <br />
        Password: <input asp-for="Password" /><br />
        Address: <input asp-for="Address.AddressLine1" /><br />
        <button type="submit">Register</button>
  • 12. What is Dependency Injection in Asp.net core? How to register and call a service?


    Dependency injection is an important technique in application programming in general and in asp.net core in particular. Dependency injection helps reduce the dependence of classes on each other while initializing them. Initializing instances of classes maybe only once for each request or when initiating the application, it helps make the short code and more maintainable.

    DI is built-in default in Asp.net core, with three method AddSingleton(), AddScoped(), AddTransient(), these three methods are equivalent to three Dependency injection lifetime Transient, Scoped and Singleton.

    To register a service in Asp.net Core, we can declare in ConfigureServices() method of Startup class. For example :

     services.AddScoped<IStudentDal, StudentDal>();

    To understand more about DI in Asp.net core you can read the article below:

    Easy way to resolve dependency injection in ASP.Net Core

  • 13. How do you implement bundle and minification Css and Js in ASP.NET Core MVC application?


    Bundle and minification Css and Js in ASP.NET Core is a step necessary and important because it helps the website load faster and helps secure code js.

    To bundle and minification Css and Js you can use some way below:

    - Use built-in tool BundlerMinifier : This available in vs2017, 2019.

    - Use Gulp js to bundle, modification and gzip Css and Js

    You can refer the article below to see detail:

    ASP.Net Core bundle, minification and gzip Css and Javascript files

  • 14. How can I get the current URL path of a webpage in a class of Asp.net Core library project?


    To get the current URL path of a webpage in a class of Asp.net Core library project we can use IHttpContextAccessor interface.

    Step 1. Declare and access interface

     public class StudentBsl
        private readonly IHttpContextAccessor _httpContextAccessor;
        public StudentBsl(IHttpContextAccessor httpContextAccessor)
            _httpContextAccessor = httpContextAccessor;
        public string GetCurrentUrl()
            string url = _httpContextAccessor.HttpContext.Request.Path;
            return url;

    Step 2. Register IHttpContextAccessor interface to DI container

    You can register line code below inside of ConfigureServices() method in Startup class.

     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
  • 15. What is the Kestrel server? Why Microsoft replace IIS to use it?


    Kestrel is a cross-platform web server for ASP.NET Core. Kestrel is the webserver that's included by default in ASP.NET Core project templates.

    As you know IIS only runs on the window can't run on Linux so Kestrel will help ASP.NET Core run on Linux.

  • 16. What is Razor Page in Asp.net core?


    Razor Pages is a new feature of ASP.NET Core MVC that can make coding page-focused scenarios easier and more productive than using controllers and views.

    If you create a project with version from 3.0 to above you can see template default is razor page. You can see like below image:

    Razor Page in Asp.net core

    Razor Pages is designed to make common patterns used with web browsers easy to implement when building an app. Model binding, Tag Helpers, and HTML helpers all just work with the properties defined in a Razor Page class

  • 17. What is response caching in ASP.NET Core? 


    Response cache is a new feature introduced in Asp.net core, Response cache help reduces the number of requests a client or proxy makes to a web server.

    Response caching also reduces the amount of work the web server performs to generate a response. Response caching is controlled by headers that specify how you want client, proxy, and middleware to cache responses.

    Response Caching middleware use middleware to store data and respond by URL path.

    For example :

     [ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
    public class Cache1Model : PageModel
      //Some code here 
  • 18. How to enable static content in Asp.net Core?


    By default when creating a project with asp.net core, in the Program.cs file you can see CreateDefaultBuilder() method. This method helps sets the content root to the current directory, The default directory is wwwroot folder.

    The default web app templates call the UseStaticFiles method in Startup.Configure, which enables static files to be served:


    If you want to change default wwwroot folder to another folder you can change app.UseStaticFiles() to below code:

     app.UseStaticFiles(new StaticFileOptions
        FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, "MyStaticFiles")), // MyStaticFiles is folder same root level with wwwroot folder
        RequestPath = "/StaticFiles"
  • 19. How to add cache header for all static files in Asp.net Core?


    To add cache header for all static files in Asp.net Core we can listen through UseStaticFiles() middleware, declare inside Configure() function of Startup class. We can add Cache-Control property to the header of the request. See the example code below:

     app.UseStaticFiles(new StaticFileOptions
        OnPrepareResponse = context =>
            // add time exprired header
            const int durationInSeconds = (60 * 60 * 24) * 365; // 1 year
            context.Context.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
  • 20. How to enable Session in Asp.net Core?


    To enable session in Asp.net Core we need to configure in 2 steps.

    Step 1: Add session service to container

    You can copy code below to put inside ConfigureServices() method of Startup class :

     // Add session to container and set timeout session
    services.AddSession(options =>
        options.IdleTimeout = TimeSpan.FromHours(2); // change time exprired session here

    Step 2: Configure the HTTP Request Pipeline

    We need to add a middleware listen to each request, Asp.net Core provided UseSession middleware, we only declare it inside the Configure() method of Startup class.