ASP.NET CORE Interview questions

 ASP. NET Core is an open-source an asp.net core training cross-platform that runs on Windows, Linux, and Mac to develop modern cloud-based applications including IoT apps, Web Apps, Mobile Backends, and more. It is the fastest web development framework from NodeJS, Java Servlet, PHP in raw performance, and Ruby on Rails. 

  1. What is the ASP.NET Core?

    ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core is completely rewriting that work with the .net Core framework. It is much faster, configurable, modular, scalable, extensible, and has cross-platform support. It can work with both .NET Core and .net framework via the .NET standard framework. It is best suitable for developing cloud-based such as web applications, mobile applications, IoT applications.

  2. 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 forDependency 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, the .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 in the startup class

    • It has good support for asynchronous programming

    • Support WebSocket and SignalR

    • Provide protection against CSRF (Cross-Site Request Forgery)

  3. What are the advantages of ASP.NET Core over ASP.NET?

    There are the 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 shipped with our application

    • ASP.NET Core can handle more requests than the ASP.NET

    • Multiple deployment options are available withASP.NET Core

  4. What is Metapackages?

    The framework .NET Core 2.0 introduced Metapackage that includes all the supported packages 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.AspNetCore.All is a meta-package provided by ASP.NET core.

  5. 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.

  6. What is the startup class in ASP.NET core?

    The 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-related items. It is not necessary that the class name must be "Startup", it can be anything, we can configure the startup class in the 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>();
     }
    
  7. What is the use of the ConfigureServices 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 the controller constructor.

  8. 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 IApplicationBuilder as a parameter and also it has two optional parameters: IHostingEnvironment and ILoggerFactory. Using this method, we can configure built-in middleware such as routing, authentication, session, etc. as well as third-party middleware.

  9. What is middleware?

    It is software that is injected into the application pipeline to handle requests and responses. They are just chained to each other and form as a pipeline. The incoming requests are passed through this pipeline where all middleware is configured, and middleware can perform some action on the request before passing it to the next middleware. Same as for the responses, they are also passing through the middleware but in reverse order.

    middleware example
  10. 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 delegates 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 or next middleware. After IApplicationBuilder.Run method, system stop adding middleware in the request pipeline.

  11. What is the use of the "Map" extension while adding middleware to the ASP.NET Core pipeline?

    It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path matching. If the request path starts with the given path, the middleware on to that branch will execute.

     
     public void Configure(IApplicationBuilder app)
     {
     app.Map("/path1", Middleware1);
     app.Map("/path2", Middleware2);
     }
    
  12. What is routing in ASP.NET Core?

    Routing is functionality that maps incoming requests to the route handler. The route can have values (extract them from URL) that are used to process the request. Using the route, routing can find a 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 to map incoming requests with the route handler and Generates URLs that are used in response. Mostly, the application has a single collection of routes and this collection is used for the process of the request. The RouteAsync method is used to map incoming requests (that match the URL) available in route collection.

  13. 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 the ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to the 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();
     ….
     ….
     }
     }
    
  14. What are the various JSON files available in ASP.NET Core?

    There are the following JSON files in ASP.NET Core :

    • global.json

    • launchsettings.json

    • appsettings.json

    • bundleconfig.json

    • bower.json

    • package.json

  15. What is a tag helper in ASP.NET Core?

    It is a feature provided by the 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# class that is used to generate the view by adding the HTML element. The functionality of the tag helper is very similar to the 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"> 
    
  16. In _ViewImport.cshtml

  17. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper *, ViewComponent Assembly Name

  18. How to disable Tag Helper at element level?

    We can disable Tag Helper at the element level using the opt-out character ("!"). This character must apply to open and close the Html tag.

    Example
     <!span asp-validation-for="phone" class="divPhone"></!span>
    
  19. 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 features 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 a code-behind file, but it is not really a code-behind file. It is a class inherited from PageModel class.

  20. How can we do the automatic model binding in Razor pages?

    The Razor pages provide the option to bind property automatically when posting the data using the BindProperty attribute. By default, it only binds the properties only with non-GET verbs. we need to set SupportsGet property to true to bind a property on getting request.

    Example
     public class Test1Model : PageModel
     {
     [BindProperty]
     public string Name { get; set; }
     }
    
  21. 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 the Service container (service can either be 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;
     }
     }
    
  22. How to specify service lifetime for register service that is 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 cleaning these dependencies, it will take care of the ASP.NET Core framework. There are three types 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 the AddSingleton method of IServiceCollection. ASP.NET Core creates a service instance at the time of registration and subsequence requests 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>();
    

    Transient

    ASP.NET Core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using the AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.

    Example
     services.AddTransient<IHelloWorldService, HelloWorldService>();
    

    Scoped

    ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service is available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while, service is registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like a singleton object.

    services.AddScoped<IHelloWorldService, HelloWorldService>();

========================================================================

1. 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 the cloud or on-premises.

2. 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 the 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 allows you to use C# code in the browser with JavaScript code.

3. What is the role of the Startup class?

The 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
    }
}

The startup class is specified inside the 'CreateHostBuilder' method when the host is created.
Multiple Startup classes can also be defined for different environments, At run time appropriate startup class is used.

4. What is the role of the ConfigureServices and Configure method?

ConfigureServices method is optional and defined inside the startup class as mentioned in the 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 IApplicationBuilder instance that's available in Configure method. Configure method also specifies how the app responds to HTTP requests and responses. ApplicationBuilder instance's 'Use...' extension method is used to add one or more middleware components to the request pipeline.
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.

5. 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 ConfigureServices method as below.

services.AddScoped();

A Service can be resolved using constructor injection and the DI framework is responsible for the instance of this service at run time. For more visit ASP.NET Core Dependency Injection

6. What problems does Dependency Injection 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 'MyDependency' with a different implementation then the class must be modified.
  • It's difficult to Unit Test.
  • If MyDependency class has dependencies then it must be configured by class. If Multiple classes have a dependency on 'MyDependency', the code becomes scattered.
DI framework solves these problems as below.
  • Use Interfaces or base classes to abstract the dependency implementation.
  • Dependencies are registered in the Service Container provided by ASP.NET Core inside the Startup class 'ConfigureServices' method.
  • Dependencies are injected using constructor injection and the instance is created by DI and destroyed when no longer needed.

7. Describe the Service Lifetimes.

When Services are registered, there is a lifetime for every service. ASP.NET Core provides the following lifetimes.

  • Transient - Services with transient lifetime are created each time they are requested from the service container. So it's best suited for stateless, lightweight 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 invoking or invoke sync 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 the first time the service is requested. For subsequent requests, the same instance is served by the service container.

8. 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 calls the next middleware component or terminates the request. When a middleware component terminates the request, it's called Terminal Middleware as It prevents the 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 a program that's built into an app's pipeline to handle the request and response. Each middleware component can decide whether to pass the request to the next component and to perform any operation before or after the next component in the pipeline.

9. What is a Request delegate?

Request delegates handle each HTTP request and are used to build a request pipeline. It can be configured using Run, Map, and Use extension methods. A request delegate can be in-line as an anonymous method (called in-line middleware) or a reusable class. These classes or in-line methods are called middleware components.

10. What is Host in ASP.NET Core?

Host encapsulates all the resources for the app. On startup, the 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

11. Describe the Generic Host and Web Host.

The host sets up the server, request pipeline and is 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 backward compatibility.

// Host creation
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup();
}

12. Describe the Servers in ASP.NET Core.

The server is required to run any application. ASP.NET Core provides an in-process HTTP server implementation to run the app. This server implementation listens for HTTP requests and surfaces them to the application as a set of request features composed into an HttpContext.
ASP.NET Core uses 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 the 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.

13. 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.
  • appsettings.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. 'CreateDefaultBuilder' method provides default configuration.

14. How to read values from the Appsettings.json file?

You can read values from appsettings.json using the 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 loads the values from appsettings.json and then from appsettings.Environment.json file.
Environment-specific values override the values from the appsettings.json file. In the development environment, appsettings.Development.json file values override the appsettings.json file values, the same applies to the production environment.
You can also read the appsettings.json values using the options pattern described Read values from the appsettings.json file.

15. What is the Options Pattern in ASP.NET Core?

Options Pattern allows you to access related configuration settings in a Strongly typed way using some classes. When you are accessing the configuration settings with the isolated classes, The app should adhere to these two principles.

  • Interface Segregation Principle (ISP) or Encapsulation: The class the depends 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.

16. How to use multiple environments in ASP.NET Core?

ASP.NET Core uses environment variables to configure application behavior based on the runtime environment. launchSettings.json file sets ASPNETCORE_ENVIRONMENT to Development on local Machine. For more visit How to use multiple environments in ASP.NET Core

17. How Logging works in .NET Core and ASP.NET Core?

18. How does Routing works in ASP.NET Core?

Routing is used to handle incoming HTTP requests for the app. Routing finds matching executable endpoint for incoming requests. These endpoints are registered when the app starts. The matching process use values from the incoming request URL to process the requests. You can configure the routing in the middleware pipeline of configuring method in the 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!");
    });
    });

For more, you can refer to ASP.NET Core Routing

19. How to handle errors in ASP.NET Core?

ASP.NET Core provides a better way to handle the errors in the Startup class as below.

    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    else
    {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
    }
 For the development environment, the Developer exception page displays detailed information about the exception. You should place this middleware before other middlewares for which you want to catch exceptions. For other environments UseExceptionHandler middleware loads the proper Error page.
You can configure error code-specific pages in the Startup class 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();
    }
    });
 For more visit Error handling

20. How does ASP.NET Core serve static files?

In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are served directly to the clients. ASP.NET Core template provides a root folder called which contains all these static files. UseStaticFiles() method inside enables the static files to be served to the client.
You can serve files outside of this webroot folder by configuring Static File Middleware as follows.


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
&lt;img src="/StaticFiles/images/profile.jpg" class="img" alt="A red rose" /&gt; // profile.jpg is image inside MyStaticFiles/images folder

23. Explain Session and State management in ASP.NET Core

As we know HTTP is a stateless protocol. HTTP requests are independent and do not retain user values. There are different ways to maintain user state between multiple HTTP requests.

  • Cookies
  • Session State
  • TempData
  • Query strings
  • Hidden fields
  • HttpContext.Items
  • Cache

24. Can ASP.NET applications be run in Docker containers?

Yes, you can run an ASP.NET application or .NET Core application in Docker containers.

24. Explain Model Binding in ASP.NET Core.

Model Binding is a process of ASP.NET Core framework to Extract Data from HTTP Requests and provide them to the arguments of Action Method.

Model binding maps data in an HTTP request to controller action method parameters.

25. Explain Custom Model Binding.

26. Describe Model Validation.

27. How to write custom ASP.NET Core middleware?

The custom middleware component is like any other .NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor.

Example: Custom Middleware

// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext httpContext)
    {

        return _next(httpContext);
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
} 

28. How to access HttpContext in ASP.NET Core?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

29. Explain the Change Token.

change token is a general-purpose, low-level building block used to track state changes.

30. How to use ASP.NET Core APIs in-class library?

31. What is the Open Web Interface for .NET (OWIN)?

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

32. Describe the URL Rewriting Middleware in ASP.NET Core.

URL Rewriting Middleware is provided by the Microsoft.AspNetCore.Rewrite package, which is implicitly included in ASP.NET Core apps.

Use AddRedirect to redirect requests. The first parameter contains your regex for matching on the path of the incoming URL. The second parameter is the replacement string. The third parameter, if present, specifies the status code. If you don't specify the status code, the status code defaults to 302 - Found, which indicates that the resource is temporarily moved or replaced.

C#

public void Configure(IApplicationBuilder app)
{
    using (StreamReader apacheModRewriteStreamReader = 
        File.OpenText("ApacheModRewrite.txt"))
    using (StreamReader iisUrlRewriteStreamReader = 
        File.OpenText("IISUrlRewrite.xml")) 
    {
        var options = new RewriteOptions()
            .AddRedirect("redirect-rule/(.*)", "redirected/$1")
            .AddRewrite(@"^rewrite-rule/(\d+)/(\d+)", "rewritten?var1=$1&var2=$2", 
                skipRemainingRules: true)
            .AddApacheModRewrite(apacheModRewriteStreamReader)
            .AddIISUrlRewrite(iisUrlRewriteStreamReader)
            .Add(MethodRules.RedirectXmlFileRequests)
            .Add(MethodRules.RewriteTextFileRequests)
            .Add(new RedirectImageRequests(".png", "/png-images"))
            .Add(new RedirectImageRequests(".jpg", "/jpg-images"));

        app.UseRewriter(options);
    }

    app.UseStaticFiles();

    app.Run(context => context.Response.WriteAsync(
        $"Rewritten or Redirected Url: " +
        $"{context.Request.Path + context.Request.QueryString}"));
}

33. Describe the application model in ASP.NET Core.

ASP.NET Core MVC defines an application model representing the components of an MVC app. Read and manipulate this model to modify how MVC elements behave. By default, MVC follows certain conventions to determine which classes are considered controllers, which methods on those classes are actions, and how parameters and routing behave. Customize this behavior to suit an app's needs by creating custom conventions and applying them globally or as attributes.

Models and Providers (IApplicationModelProvider)

The ASP.NET Core MVC application model includes both abstract interfaces and concrete implementation classes that describe an MVC application. This model is the result of MVC discovering the app's controllers, actions, action parameters, routes, and filters according to default conventions. By working with the application model, modify an app to follow different conventions from the default MVC behavior. The parameters, names, routes, and filters are all used as configuration data for actions and controllers.

The ASP.NET Core MVC Application Model has the following structure:

  • ApplicationModel
    • Controllers (ControllerModel)
      • Actions (ActionModel)
        • Parameters (ParameterModel)

Conventions

The application model defines convention abstractions that provide a simpler way to customize the behavior of the models than overriding the entire model or provider. These abstractions are the recommended way to modify an app's behavior. Conventions provide a way to write code that dynamically applies customizations. While filters provide a means of modifying the framework's behavior, customizations permit control over how the whole app works together.

The following conventions are available:

Conventions are applied by adding them to MVC options or by implementing attributes and applying them to controllers, actions, or action parameters (similar to filters).Unlike filters, conventions are only executed when the app is starting, not as part of each request.

34. 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 the actual data sources. It also improves scalability. Response caching is best suited for data that changes infrequently. Caching makes the copy of data and stores it instead of generating data from the original source.
Response caching headers control the response caching. ResponseCache attribute sets these caching headers with additional properties.

35. What is an In-memory cache?

In-memory cache is the simplest way of caching by ASP.NET Core that stores the data in memory on a web server.
Apps running on multiple servers should ensure that sessions are sticky if they are using an in-memory cache. Sticky Sessions is responsible to redirect subsequent client requests to the same server. The in-memory cache can store any object but distributed cache only stores byte[].
IMemoryCache interface instance in the constructor enables the In-memory caching service via ASP.NET Core dependency Injection.

36. 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 servers
  • Data keeps alive during server restarts and deployments.
  • Data does not use local memory

IDistributedCache interface instance from any constructor enables distributed caching service via Dependency Injection.

37. 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 an attacker that acts as a trusted source sends some data to a website and performs some action. An attacker is considered a trusted source because it uses the authenticated cookie information stored in the browser.
For example, a user visits some site 'www.abc.com' then the browser performs authentication successfully and stores the user information in the 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 a vulnerable site (www.abc.com). It's called the cross-site part of CSRF.
How to prevent CSRF?

  • In ASP.NET Core 2.0 or later FormTaghelper automatically injects the anti-forgery tokens into the HTML form element.
  • You can add manually an anti-forgery token in HTML forms by using and then you can validate it in the controller by the method.
  • For more, you can visit Prevent Cross-Site Request Forgery (XSRF/CSRF)

38. How to prevent Cross-Site Scripting (XSS) in ASP.NET Core?

39. How to enable Cross-Origin Requests (CORS) in ASP.NET Core?

Browser security prevents a web page located on a domain to make requests to a web page that is located on a different domain. This restriction is called the same-origin policy.

Once a website enables CORS, new HTTP headers are introduced which enable cross-origin requests. These HTTP headers are automatically set for cross-origin requests. One important HTTP header is called Access-Control-Allow-Origin. So when an external page or resource, makes requests to a resource (like a page, file, etc) on another Server or domain, then this server responds with a value for the Access-Control-Allow-Origin header.

Many times, this value will be *, meaning that the Server will share the requested resources with any domain on the Internet. Other times, the value of this header may be set to a particular domain (or list of domains), meaning that the Server will share its resources with that specific domain (or list of domains).

An ASP.NET Core website can enable CORS quite easily. You just need to follow below steps:

  • 1. Install Microsoft.AspNetCore.Cors NuGet package.
  • 2. Register CORS in the ConfigureService() method of Startup.cs.
  • 3. Enable CORS using middleware in the Configure() method of Startup.cs.
You need to Register the CORS service in the Startup.cs file’s ConfigureServices() method as shown below:
1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllersWithViews();
}

Next you need to add the CORS middleware to your app. In your Startup.cs you should have a Configure() method. You need to have it similar to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
 
    app.UseHttpsRedirection();
 
    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
    {
        builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
 
    app.UseStaticFiles();
 
    app.UseRouting();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Notice I added the code line with the option AllowAnyOrigin to accept any domain that makes CORS request:

1
2
3
4
5
6
7
app.UseCors(builder =>
{
    builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
});

I have also used other method which are described below:

  • 1. AllowAnyMethod() – To allow all HTTP methods.
  • 2. AllowAnyHeader() – To allow all request headers.
  • 3. AllowCredentials() – the server must allow the credentials.

If you want to enable CORS for request made from 1 domain only like https://www.yogihosting.com then change the above code to:

1
2
3
4
5
6
7
8
app.UseCors(builder =>
{
    builder
    .WithOrigins("https://www.yogihosting.com")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});

You can specify more than 1 domain like this:

1
2
3
4
5
6
7
8
app.UseCors(builder =>
{
    builder
    .WithOrigins(new string[] { "https://www.yogihosting.com", "https://example1.com", "https://example2.com" })
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});

Apply CORS policies per action or per controller

Define one or more named CORS policies and select the policy by name at runtime. See the following example which adds a user-defined CORS policy named as MyPolicy.

To select the policy, pass the name to the UseCors() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyPolicy",
            builder => builder.WithOrigins("https://www.yogihosting.com"));
    });
 
    services.AddControllersWithViews();
}
 
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
 
    app.UseHttpsRedirection();
 
    // Shows UseCors with named policy.
    app.UseCors("MyPolicy");
 
    app.UseStaticFiles();
 
    app.UseRouting();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now you can apply this CORS policy per action or per controller.

Per Action

To specify a CORS policy for a specific action, add the [EnableCors] attribute of Microsoft.AspNetCore.Cors namespace to the action and specify the policy name:

1
2
3
4
5
[EnableCors("MyPolicy")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Per controller

1
2
[EnableCors("MyPolicy")]
public class HomeController : Controller

To disable CORS for a controller or action, use the [DisableCors] attribute:

1
2
3
4
5
[DisableCors]
public string Get(int id)
{
    return "value";
}

40. What is the Area?

The area is used to divide large ASP.NET MVC applications 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 an MVC structure that separates an application into multiple functional groupings. For example, for an e-commerce site Billing, Orders, search functionalities can be implemented using different areas.

41. Explain the Filters.

Filters provide the capability to run the code before or after the specific stage in the request processing pipeline, it could be either the MVC app or Web API service. Filters perform the tasks like Authorization, Caching implementation, Exception handling, etc. ASP.NET Core also provides 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. OnResourceExecuting the filter runs the code before the rest of the filter pipeline and runs the code after resting of the filter pipeline.
  • Action filters run the code immediately before and after the action method execution. Action filters can change the arguments passed to the method and can change the returned results.
  • Exception filters are used to handle the exceptions globally before writing the response body
  • Result filters allow running the code just before or after the successful execution of action results.

42. Describe the View components in ASP.NET Core.

public class
HeadCountViewComponent : ViewComponent
{
    private readonly IEmployeeRepository _employeeRepository;
    public HeadCountViewComponent(IEmployeeRepository employeeRepository)
    {
        this._employeeRepository = employeeRepository;
    }

    public IViewComponentResult Invoke()
    {
        var result = _employeeRepository.EmployeeCountByDept();
        return View(result);
    }
}


@await Component.InvokeAsync("HeadCount")

43. How View compilation works in ASP.NET Core?

44. Explain Buffering and Streaming approaches to upload files in ASP.NET Core.

For more information visit ASP.NET CORE Upload files

ASP.NET Core MVC Interview Questions

1. 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 separates an application into three main components known as Model, View, and Controller. It also helps to achieve the SoC (Separation of Concern) design principle.
ASP.NET Core MVC is a lightweight, open-source, and testable framework to build web applications and services.

2. Explain the Model, View, and Controller.

ASP.NET MVC has three main groups of components Model, View, and Controller, Each one has its own responsibilities as below.

  • Model - It contains the business logic and represents the state of an application. It also performs the operation on the data and encapsulates the logic to persist an application state. Strongly-typed Views use the View-Model pattern to display the data in the view.
  • View - It's responsible to present the content via the User interface. It does not contain much logic and uses Razor View Engine to embed .NET code into view. If you need to perform much logic to display the data then prefer to use View Component, View Model, or View Template for simplifying the view.
  • Controller - It's responsible to handle user interactions, It works with the model and selects the view to display. The controller is the main entry point that decides the model with which it works and decides which view it needs to display. Hence its name - Controller means controls user inputs and interactions.

3. Explain View-Model.

ViewModel is used to pass complex data from controller to view. ViewModel data is prepared from different models and passed to view to display that data. For example, A Complex data model can be passed with the help of ViewModel.


    Class Author{
    public int Id {get;set;}
    public Book Book {get;set;}
    }
    Class Book{
    public string Name {get;set;}
    public string PublisherName {get;set;}
    }

This Author and Book data can be passed to view by creating Author ViewModel inside the controller.

4. Explain strongly-typed views.

Strongly-typed views are tightly bound to a model. for example, In the above question if you want to pass the author data to view then you need to write the below code for type checking in your view. @model Author. A controller can pass a strongly type model to view that enables type checking and IntelliSense support in view.

5. Explain Partial Views.
<partial name="_PartialName" />

When a file extension is present, the Tag Helper references a partial view that must be in the same folder as the markup file calling the partial view:

<partial name="_PartialName.cshtml" />

6. How routing works in MVC applications?

7. Describe Attribute-based routing.

Attribute Routing gives you more control over the URIs in your web application. MVC 5 supports this attribute-based routing where attributes are used to define the routes. You can manage resource hierarchies in a better way using attribute-based routing. Attribute-based routing is used to create routes that are difficult to create using convention-based routing. For example below routes.

[Route("customers/{customerId}/orders")]
public IEnumerable GetOrdersByCustomer(int customerId) { ... }
        .
        .
        .
[Route("customers/{customerId}/orders/orderId")]
public IEnumerable GetOrdersByCustomer(int customerId, int orderId) { ... }

8. Explain dependency injection for controllers.

9. How ASP.NET Core supports dependency injection into views?

The syntax for @inject@inject <type> <name>

An example using @inject:

@using Microsoft.Extensions.Configuration

@inject IConfiguration Configuration

@{

   string myValue = Configuration["root:parent:child"];

   ...

}

10. How will you unit test a controller?

11. What is Cache Tag Helper in ASP.NET Core MVC?
The Cache Tag Helper provides the ability to improve the performance of your ASP.NET Core app by caching its content to the internal ASP.NET Core cache provider.

<cache enabled="true">

    Current Time Inside Cache Tag Helper: @DateTime.Now

</cache>

<cache expires-on="@new DateTime(2025,1,29,17,02,0)">

    Current Time Inside Cache Tag Helper: @DateTime.Now

</cache>

12. How validation works in MVC and how do they follow DRY Pattern?

13. Describe the complete request processing pipeline for ASP.NET Core MVC.







Comments

  1. Harrah's Cherokee Casino & Hotel - Trip.com
    Find all 충청남도 출장샵 information and best deals of Harrah's Cherokee Casino & Hotel, Murphy, NC 화성 출장샵 on Trip.com! Book 삼척 출장안마 the hotel with real traveler 수원 출장샵 reviews,  화성 출장안마 Rating: 4.1 · ‎1 review

    ReplyDelete

Post a Comment

Popular posts from this blog

SQL Interview Questions and Answers

Generic Interface and Factory Pattern in C#

How to get device info IMEI programmatically in xamarin android