Tech Point Fundamentals

Sunday, November 6, 2022

.Net Core Interview Questions and Answers - Part 10

ASP.Net Core Interview Questions and Answers - Part 10

AspDotNetCoreInterviewQuestionsAndAnswers

Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 10th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:






ASP.Net Core Interview Questions and Answers - Part 10


Q094. What is Middleware in ASP.NET Core? How it is different from HttpHandlers and HttpModules of classic ASP.Net?

ASP.NET Core introduced a new concept called Middleware.  Middleware is software that's assembled into an app pipeline to handle requests and responses. Middleware controls how our application responds to HTTP requests. 

In general, middleware is plumbing software that facilitates communication flow between two components. In a web application framework, middleware provides common services and capabilities to the application outside of the default framework.

Each middleware component in ASP.NET Core Application:

  1. Chooses whether to pass the request to the next middleware component in the pipeline.
  2. Can perform work before and after the next middleware component in the pipeline.

A middleware is nothing but a component (class) that is executed on every request in the ASP.NET Core application. So middleware actually refers to the C# classes that manipulate an HTTP request when it comes in or an HTTP response when it’s on its way out. 



In the classic ASP.NET, HttpHandlers and HttpModules were part of the request pipeline. Middleware is similar to HttpHandlers and HttpModules where both need to be configured and executed in each request.

Inside the request pipeline, an application executes each component in the same order they are placed in the code – top to bottom. We can see that each component can execute custom logic before using the next delegate to pass the execution to another component:
middleware
Source: Microsoft Docs

The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. Each delegate can perform operations before and after the next delegate.



Each Middleware is injected into the application pipeline to handle requests and responses. Each middleware adds or modifies the HTTP request and optionally passes control to the next middleware component.

A Middleware is able to call another and this middleware calls another middleware and so on this is called a pipeline. 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. 


Terminal Middleware:

Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it's called terminal middleware because it prevents further middleware from processing the request. It prevents the next middleware from processing the request. 

Usually, the last middleware component doesn’t call the next delegate, which means that this component is short-circuiting the pipeline. This is a terminal middleware because it stops further middleware from processing the request. Basically, it executes the additional logic and then returns the execution to the previous middleware components.




Q095. What is the use of the Middleware in the ASP.Net Core App?

All ASP.NET Core applications need a minimum of one piece of middleware to respond to requests and your applications are effectively just a collection of middleware. Even the MVC pipeline itself is middleware.

Middlewares build the request pipeline. These middleware components are configured as part of the application startup class in the configure method.

It gives you control over the order in which the requests should be executed, unlike ASP.NET Core HTTP modules. 

Middleware is used to implement several tasks when handling requests. Such examples include authentication, session state retrieval and persistence, logging, and much more. 




Q096. Where the Middlewares are registered in the .Net Core Application?

Middlewares are registered under the Configure method in the Startup.cs file. Asp.net Core has many built-in middlewares which can be added via Nuget or we can also create custom middleware.

Middleware is configured by code rather than the web.config in traditional  ASP.NET. In the ASP.Net Core, it is found inside your Startup.cs file. We can register as much middleware as we want, but the ordering is important.



Q097. What is the order of Middlewares in the .Net Core App? Why ExceptionHandler middleware is placed very first in ASP.NETCore?

The topmost middleware of the application will always get called for each request. This is done automatically by the framework. This middleware may send a response to the client,  or it may call the next piece of middleware.

It is very important to understand the execution order of Middleware components. The ASP.NET Core middleware components are executed in the same order as they are added to the pipeline. So, we need to take care when adding the middleware components to the request processing pipeline.

It is very important to understand the order in which we should register our middleware components. The order is important for the security, performance, and functionality of our applications:



Middleware-Order-of-Configuration
Source: code-maze


The exception handler middleware is registered in the early stage of the pipeline flow so it could catch all the exceptions that can happen in the later stages of the pipeline.



So the Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline. 

Since the UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.

Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. The Static File Middleware provides no authorization checks. Any files served by Static File Middleware, including those under wwwroot, are publicly available. 

Authentication doesn't short-circuit unauthenticated requests. Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.

The Endpoint middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages. The EndPoint Middleware basically calls and executes the following:



endpoint-middleware
Source: Microsoft Docs

The order that middleware components are added in the Program.cs file defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.



Q098. How can you configure the Middleware Component in ASP.Net Core? What is the use of Configure() method?

We can configure the Middleware components within the Configure() method of the Startup class which is present inside the Startup.cs file. This is the class that is going to run when the application starts.

When we create an ASP.NET Core application with an Empty Template, then by default the Startup class is created with the Configure() method. 

A middleware component can be configured within the Configure() method of the Startup class by calling the Use* methods on the IApplicationBuilder object.



public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseRouting();
    app.UseCors();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseResponseCaching();
    //Custom middleware components
    app.UseEndpoints(endpoints =>
    {
       ...
    });
}



Q099. What is Request Delegate in .Net Core?

In ASP.NET Core, Request delegates are used to build the request pipeline. They are used to handle each incoming HTTP request. In ASP.NET Core, you can configure the Request delegates using the Run, Map, and Use extension methods. 

An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components.

Each middleware component in the request processing pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline by not calling the next middleware component.



Q100. What is the difference between app.Use() and app.Run() methods in .Net Core? 

In ASP.NET Core, you can use both the “Use” and “Run” extension methods to register the inline Middleware component into the Request processing pipeline.

The only difference between them is that the RUN() method is used to add the terminating middleware while the USE() extension method allows us to add the middleware components which may call the next middleware component in the request processing pipeline.

So the Run() extension method does not call the next middleware components in the request processing pipeline but the Use() method will do. 

It means app.Run acts as a terminal middleware, so no other middleware method will run after this. Hence, use Run() either for the last middleware or if there is no middleware to execute after that.



Q101. How to Configure Middleware Components using the Use() extension method?

To chain multiple request delegates in our code, we can use the Use method. The next parameter represents the next delegate in the pipeline. 

You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate.

The Use() method accepts a Func delegate as a parameter and returns a Task as a result. So, this means when we use it, we can make use of two parameters, context and next:

app.Use(async (context, next) =>
{
Console.WriteLine($"Logic before executing the next delegate in the Use method");
await next.Invoke();
Console.WriteLine($"Logic after executing the next delegate in the Use method");
});

The Run method doesn’t accept the next delegate as a parameter, so without it to send the execution to another component, this component short-circuits the request pipeline.



Q102. How to Configure Middleware Components using the Run() extension method?

When a delegate doesn't pass a request to the next delegate, it's called short-circuiting the request pipeline.  Short-circuiting is often desirable because it avoids unnecessary work. The Run() is used for adding a short-circuiting request pipeline. 

For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline.

Inside the Configure method, we can use an anonymous method to create a first Run middleware component:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{    
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello from the middleware component.");
    });
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}



Run delegates don't receive the next parameter. The first Run delegate is always terminal and terminates the pipeline. Run is a convention.

We use the Run method, which adds a terminal component to the app pipeline. We can see that we are not using the other next delegate because the Run method is always terminal and terminates the pipeline. 

This method accepts a single parameter of the RequestDelegate type. If you inspect the Run delegate you are going to see that it accepts a single HttpContext parameter. In this specific example, we are modifying the response by using the WriteAsync method.



Q103. What is the use of next.Invoke() method in .Net Core? What are the limitations of using this?

The next.Invoke() method is used to invoke the next middleware within the Use() method. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke() statements.

We shouldn’t call the next.Invoke after we send the response to the client. This can cause exceptions if we try to set the status code or modify the headers of the response.

Writing to the response body after calling next may cause a protocol violation or may corrupt the body format. 



app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hello from the middleware component.");
    await next.Invoke();
    Console.WriteLine($"Logic after executing the next delegate in the Use method");
});
app.Run(async context =>
{
    Console.WriteLine($"Writing the response to the client in the Run method");
    context.Response.StatusCode = 200;
    await context.Response.WriteAsync("Hello from the middleware component.");
});

Here we write a response to the client and then call next.Invoke. Of course, this passes the execution to the next component in the pipeline. There, we try to set the status code of the response and write another one. But It will not work and generate an error:

NextMethodError


To Be Continued Part-11...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

    

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.