Tech Point Fundamentals

Sunday, November 13, 2022

.Net Core Interview Questions and Answers - Part 11

ASP.Net Core Interview Questions and Answers - Part 11

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 11th 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 to the current part:






ASP.Net Core Interview Questions and Answers - Part 11


Q104. What is Forwarded Headers Middleware in .Net Core? What should be their order in the middleware?

When HTTPS requests are proxied over HTTP, the original scheme (HTTPS) is lost and must be forwarded in a header. Because an app receives a request from the proxy and not its true source on the Internet or corporate network, the originating client IP address must also be forwarded in a header.

This information may be important in the request processing, for example in redirects, authentication, link generation, policy evaluation, and client geolocation.

By convention, proxies forward information in HTTP headers like X-Forwarded-For (XFF), X-Forwarded-Proto (XFP), and X-Forwarded-Host (XFH). The Forwarded Headers Middleware, ForwardedHeadersMiddleware, reads these headers and fills in the associated fields on HttpContext.

Forwarded Headers Middleware should run before other middleware. This ordering ensures that the middleware relying on forwarded header information can consume the header values for processing. 

Forwarded Headers Middleware can run after diagnostics and error handling, but it must be run before calling UseHsts.




Q105. What is the difference between MapGet() and Map() methods?

The MapGet method is going to handle the GET HTTP Requests whereas the Map method is going to handle all types of HTTP requests such as GET, POST, PUT, & DELETE, etc.

Map() Method:

The Map method is an extension method that accepts a path string as one of the parameters:

public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration)

When we provide the path match string, the Map method will compare it to the start of the request path. If they match, the app will execute the branch.



By using the Map method, we provide the path match, and then in the delegate, we use our well-known Use and Run methods to execute middleware components.

app.Map("/map1", HandleMapRequestPath);

static void HandleMapRequestPath(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Mapped RequestPath");
});
}

When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request. The map() can also match multiple segments at once:

app.Map("/map1/seg1", HandleMultiSeg);

The Map() supports nesting as well.



MapGet() Method:

This method uses the result of the given predicate to branch the request pipeline. MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline. 

If we inspect the MapWhen method, we are going to see that it accepts two parameters:

public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Func<HttpContext, bool> predicate, Action<IApplicationBuilder> configuration);

If our request contains the provided query string, we execute the Run method by writing the response to the client. 

app.MapWhen(context => context.Request.Query.ContainsKey("testquerystring"), builder =>
{
builder.Run(async context =>
{
await context.Response.WriteAsync("Hello from the MapWhen branch.");
});
});




Q106. What are the different built-in middlewares in ASP.Net Core?

ASP.NET Core ships with the following 25 inbuilt middleware components:

1. Authentication: It provides authentication support. It is called before HttpContext.User is needed.

2. Authorization: It provides authorization support. It is called immediately after the Authentication Middleware.

3. Cookie Policy: It tracks consent from users for storing personal information and enforces minimum standards for cookie fields, such as secure and SameSite. It invoked before middleware that issues cookies. Examples: Authentication, Session, MVC (TempData).
4. CORS: It is for Configures Cross-Origin Resource Sharing.

5. DeveloperExceptionPage: It generates a page with error information that is intended for use only in the Development environment.

6. Diagnostics: Several separate middlewares that provide a developer exception page, exception handling, status code pages, and the default web page for new apps.

7. Forwarded Headers: Forwards proxied headers onto the current request.



8. Header Propagation: Propagates HTTP headers from the incoming request to the outgoing HTTP Client requests.

9. Health Check: Checks the health of an ASP.NET Core app and its dependencies, such as checking database availability.

10. HTTP Logging: Logs HTTP Requests and Responses.

11. HTTP Method Override: Allows an incoming POST request to override the method.

12. HTTPS Redirection: Redirect all HTTP requests to HTTPS.

13. HTTP Strict Transport Security (HSTS): Security enhancement middleware that adds a special response header.

14. MVC: Processes requests with MVC/Razor Pages.

15. OWIN: Interop with OWIN-based apps, servers, and middleware.

16. Response Caching: Provides support for caching responses.



17. Response Compression: Provides support for compressing responses.

18. Request Localization: Provides localization support.

19. Endpoint Routing: Defines and constrains request routes.

20. SPA: Handles all requests from this point in the middleware chain by returning the default page for the Single Page Application (SPA).

21. Session: Provides support for managing user sessions.

22. Static Files: Provides support for serving static files and directory browsing.

23. URL Rewrite: Provides support for rewriting URLs and redirecting requests.

24. W3CLogging: Generates server access logs in the W3C Extended Log File Format.

25. WebSockets: Enables the WebSockets protocol.




Q107. How can you create your own custom middleware and register it in the middleware in .Net Core?

There is two way to create and register a middleware i.e. conventional and factory-based. Let's see the conventionally based middleware creation here:

First, create a new CustomMiddleware class in the root of the app:

public class MyCustomMiddleware
{
private readonly RequestDelegate _next;
public MyCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine("My Custom Middleware logic");
await _next.Invoke(context);
}
}



The conventional way uses constructor injection to provide the RequestDelegate next parameter. Here, we are injecting the RequestDelegate next parameter and use it inside the InvokeAsync method to pass the execution to the next component. 

It is important that our middleware contains a public constructor with the injected RequestDelegate parameter and the method named Invoke or InvokeAsync.

After this, we can create another wrapper class and place a single extension method inside:

public static class MiddlewareExtension
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
=> builder.UseMiddleware<CustomMiddleware>();
}

We created a static method that returns an IApplicationBuilder as a result and extends the IApplicationBuilder interface. In the method’s body, we just call the UseMiddleware method to add our custom middleware to the application’s pipeline.

Finally, we have to modify the Configure method in the Startup class below the first Use method:

app.UseCustomMiddleware();

Single or multiple Middleware can be used in the .Net Core application.



Q108. What is the difference between IMiddleware and IMiddlewareFactory Interface? When we should use Factory-Based Middleware in the .Net Core?

Both IMiddlewareFactory and IMiddleware are extensibility points for middleware activation. Both Interfaces define a middleware that can be added to the application's request pipeline.  They offer:

  • Activation per client request ((via scoped services injection )
  • Strong typing of middleware

IMiddleware Interface vs IMiddlewareFactory:

IMiddleware defines middleware for the app's request pipeline. Since the IMiddleware is activated per client request (connection), so scoped services can be injected into the middleware's constructor.

The InvokeAsync(HttpContext, RequestDelegate) method handles requests and returns a Task that represents the execution of the middleware.

IMiddlewareFactory provides methods to create middleware. The middleware factory implementation is registered in the container as a scoped service.

The default IMiddlewareFactory implementation, MiddlewareFactory, is found in Microsoft.AspNetCore.Http package.



Creating Factory-Based Middleware:

In the previous custom middleware implementation (in Q107) in the MiddlewareExtension class, we called the UseMiddleware method to add the custom middleware to the application’s pipeline.

UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.

Let's create a new FactoryActivatedCustomMiddleware class that implements the IMiddleware interface.

public class FactoryActivatedCustomMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
Console.WriteLine("Factory Activated Custom Middleware logic from the separate class.");
await next.Invoke(context);
}
}

Here we don’t have to use constructor injection to provide the RequestDelegate next parameter like we did in Q104.  In this case, we have that parameter inside the InvokeAsync method that we have to implement due to the IMiddleware’s contract implementation.



Now we have to create Extensions for the created middleware. We can either create a new class or add a new method UseFactoryActivatedCustomMiddleware() in the MiddleareExtension wrapper class which we have created in Q106:

public static class MiddlewareExtension
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
=> builder.UseMiddleware<CustomMiddleware>();
public static IApplicationBuilder UseFactoryActivatedCustomMiddleware(this IApplicationBuilder builder)
=> builder.UseMiddleware<FactoryActivatedCustomMiddleware>();
}

If you inspect the UseMiddleware method, you can see that it accepts the params object[] args parameter. But for the factory-activated middleware, passing any parameter to the UseMiddleware method will cause the NotSupportedException at runtime.

public static IApplicationBuilder UseFactoryActivatedMiddleware( this IApplicationBuilder app, bool option)
{
// Passing 'option' as an argument throws a NotSupportedException at runtime.
return app.UseMiddleware<FactoryActivatedMiddleware>(option);
}



So it isn't possible to pass objects to the factory-activated middleware with UseMiddleware.

The factory-activated middleware should be added to the built-in container in Program.cs. So we have to register our factory middleware in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<FactoryActivatedCustomMiddleware>();
services.AddControllers();
}

Finally, we can call our extension method in the Configure method:

app.UseCustomMiddleware();
app.UseFactoryActivatedCustomMiddleware();




Q109. What is the difference between synchronous and asynchronous middleware?

The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate. You can either specify a lambda expression or specify a function in the Run method.

public class Startup
{
    public Startup()
    {
    } 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    { 
app.Run(MyCustomSynMiddleware);   
    }
    private Task MyCustomSynMiddleware(HttpContext context) 
    {
        return context.Response.WriteAsync("Sync Middleware ");
    }
}

The above MyCustomSynMiddleware function is not asynchronous and so will block the thread till the time it completes the execution. So, make it asynchronous by using async and await to improve performance and scalability.

private async Task MyCustomSynMiddleware(HttpContext context) 
{
    await context.Response.WriteAsync("Async Middleware ");
}



Q110. How can you configure multiple middleware in .Net Core?

Usually, there are multiple middleware components in the ASP.NET Core application that will be executed sequentially.

Since the Run method adds a terminal middleware so it cannot call the next middleware as it would be the last middleware in a sequence. 

Therefore to configure multiple middlewares, we need to use the Use() extension method. It is similar to the Run() method except that it includes the next parameter to invoke the next middleware in the sequence. 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("First Middleware");
        await next();
    });

    app.Run(async (context) =>
    {
await context.Response.WriteAsync("Second Middleware"); 
    });
}




Q111. How can you configure the default file in the .Net Core Application?

We can configure a Default File to be served on the Root Request. The app.UseDefaultFiles() middleware serves the following files on the root request.

  1. Default.html
  2. Default.htm
  3. Index.html
  4. Index.htm

If you want to set Index.html as a default page which should be displayed on the root access. To do that, specify DefaultFilesOptions in the UseDefaultFiles method:

public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("Index.html");
app.UseDefaultFiles(options);

app.UseStaticFiles();
}
}



Q112. What is the difference between Httphandler, Httpmodules, and ASP.NET Core Middleware?

HttpHandler:

The purpose of HttpHandler in standard web applications is to handle the incoming request and process it and detect the particular resource depending on the extension. 

Any HttpHandler implements IHTTPHandler. HttpHandler is also called Extension Based Request preprocessor. Httphandler processes the request and sends the response back to the browser.

IHTTPHandler has one method and one property: IsReusable and ProcessRequest(). 

The ProcessRequest() take the HttpContext as a parameter. HttpContext contains many properties, among them 2 important are request and response. By using this request property, we can get all the information sent via HttpRequest such as domain name, query string values, request meta values, and so on.



HttpModule:

Basically, when a request is raised for a resource to a web application, there are some events which take place before the request is ultimately processed and the resource is returned. 

These events are the ones that do some checks on the request before it can be processed and the resource is produced fresh from the webserver. 

The HttpModules work on these events and perform some extra logic on the request. HttpModule can be attached to any event on the basis of the business requirement.

Httpmodules handle the requests-based events but should have a complete understanding on the request state.

The main events that the request goes through are as follows:  BeginRequest, AuthenticateRequest, AuthorizeRequest, PreRequesthandlerRexecute, PostRequesthandlerExecute, EndRequesst. 

These are the events where Modules can be attached to inject some extra logic for this event, acting on a request.



HttpModule implements IHttpModule. IHttpModule has two methods - init(HttpApplication), Dispose(). 

HttpApplicationobject exposes all the events of the application which will act on the request before it's processed by the HttpHandler.

An application's event can have more than one module acting on it. Whereas only one HttpHandler processes on a request specific to a type.  One type of request cannot be processed by 2 different HttpHandlers. This is a major difference between HttpHandler and HttpModule.

Middleware:

In ASP.Net Core middleware has replaced both handlers and modules. Middleware is a component in asp.net core through which every request will pass and be processed as per the need. Middleware can short-circuit the processing of the request and pass on the response back to the requestor.

.NET Core middleware pipeline requests transferred between different middleware generate the response. The pipeline is defined in code so that we have control over request transition. you can change the order whenever you want.




Q113. How can you disable middleware in ASP.NET Core?

By using HttpContext class Features property we can disable any middleware.

Public void Code()
{
var StatusCodeFeature = HttpContext.Features<IStatusCodePagesFeatures>();
if(StatusCodeFeature != null && StatusCodeFeature.Enabled )
{
StatusCodeFeature .Enabled = false;
}
}


To Be Continued Part-12...


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.